Reading Data From a Text File with Swift - swift

For example I have a list of some items in a text file. I want to read that data one by one. How can I do that in Swift? I've found NSString.stringWithContentsOfFile(path) but this reads whole file. In C++ i was using ifstream for that. Example:
ifstream fd(fileName);
string code, type, title;
int price, date;
getline(fd, title);
while (!fd.eof()) {
getline(fd, code, ',');
fd >> ws;
getline(fd, type, ',');
fd >> ws;
fd >> date;
fd.ignore();
fd >> price;
fd.ignore();
}
fd.close();
And sample text file for that:
Title of List
K123, document, 1994, 12500
S156, photo, 2006, 7000
R421, book, 1998, 6000
How can I read files with Swift like that and get words in it one by one?

Is it appropriate for you to read the whole file and then just parse the string into an array of characters/words? If so, consider using
func componentsSeparatedByString(_ separator: String) -> [AnyObject]
If you know there is a space or comma or whatever separator in between each token, this could be a possible solution. If that's not acceptable just comment below.

Related

Is it possible to build a list from a carriage return separated string?

Background
I have the following string:
var MyString = 'Test1⏎Test2⏎Test3⏎Test4'
⏎ = line feed = \n
What I'm trying to do
I want to create a List which is a list of lines. Basically every item that is followed by a \n would become an entry in the list.
I want the base string MyString to become shortened to reflect what pieces of the string have been moved to the List
The reason I want to leave a residual MyString is that new data might come in later that might be considered part of the same line, so I do not want to commit the data to the List until there is a carriage return seen
What the result of all this would be
So in my above example, only Test1 Test2 Test3 are followed by \n but not Test4
Output List would be: [Test1, Test2, Test3]
MyString would become: Test4
What I've tried and failed with
I tried using LineSplitter but it seems to want to take Test4 as a separate entry as well
final lines = const LineSplitter().convert(MyString);
for (final daLine in lines) {
MyList.add(daLine);
}
And it creates [Test1, Test2, Test3, Test4]
A solution would be to just .removeLast() on the list that you split.
String text = 'Test1\nTest2\nTest3\nTest4';
List<String> list = text.split('\n');
text = list.removeLast();
print(list); // [Test1, Test2, Test3]
print(text); // Test4
To me you are combining two questions. Every language I know has built-in ways to split a string on a char, including newline chars. The distinct thing you want is a split function that doesn't include the last entry.
You may be combining your answers as well :) Is there some resource constraint or streamed input that prevents you from just building the list, then popping off the final entry?
If yes:
I think you have to build your own split. Look at the implementation code for LineSplitter(), and make something similar except which leaves the final entry.
If no:
simply call
MyString = MyList.removeLast();
after your for-loop.

How do I parse out a number from this returned XML string in python?

I have the following string:
{\"Id\":\"135\",\"Type\":0}
The number in the Id field will vary, but will always be an integer with no comma separator. I'm not sure how to get just that value from that string given that it's string data type and not real "XML". I was toying with the replace() function, but the special characters are making it more complex than it seems it needs to be.
is there a way to convert that to XML or something that I can reference the Id value directly?
Maybe use a regular expression, e.g.
import re
txt = "{\"Id\":\"135\",\"Type\":0}"
x = re.search('"Id":"([0-9]+)"', txt)
if x:
print(x.group(1))
gives
135
It is assumed here that the ids are numeric and consist of at least one digit.
Non-regex answer as you asked
\" is an escape sequence in python.
So if {\"Id\":\"135\",\"Type\":0} is a raw string and if you put it into a python variable like
a = '{\"Id\":\"135\",\"Type\":0}'
gives
>>> a
'{"Id":"135","Type":0}'
OR
If the above string is python string which has \" which is already escaped, then do a.replace("\\","") which will give you the string without \.
Now just load this string into a dict and access element Id like below.
import json
d = json.loads(a)
d['Id']
Output :
135

How can I extract all text between different sets of strings in Swift?

For example I want to extract all text that sits between any one of these string combinations:
[["<p>", "</p>"], ["<h4>", "</h4>"]]
This string:
"<h4>Food</h4> random stuff <p>Is good</p> more random stuff <p>When hot</p>"
should give me this result:
["<h4>Food</h4>", "<p>Is good</p>", "<p>When hot</p>"]
Note: It is important that the string combination used to extract the text remain in the final array as shown above.

Add the date of creation to a filename in SystemVerilog

I need to create a report(.txt) and I want to reference each sessions of tests, so I wanted that for each simulations, I add the date to name of my report.
Like Report_01-19-2017-12:53.txt
So far I have been able to create either a file with the date inside with :
$system("date > sDate");
or display it on my simulation software with :
$system("date");
So far,My code look like :
string filename;
reg [8*30:1] data; // the date is of 29 characters in size
string sDate;
integer scan_file,data_file ;
initial begin
$system("date > data");
data_file = $fopen("data", "r");
scan_file = $fscanf(sDate,"%s", data);
$fclose("data");
[...]
filename = {filename,sDate};
Report_Task = $fopen(filename,"a"); [...]
end
sDate contains nothing, date contains the date...
I tried string and reg for filename and sDate
Instead of going through files to get the date, you could use svlib. Chapter 9 of the documentation illustrates how to get information about the current time.
Don't you mean
scan_file = $fscanf(data_file, "%s", sDate);
where, if the read is successful, scan_file will be equal to 1 (the number of items read). (So, you probably didn't want to call it scan_file.)

How to return next string without >> with stringstream?

Instead of:
stringstream szBuffer;
szBuffer>>string;
myFunc(string);
How do I do like:
muFunc(szBuffer.NextString());
I dont want to create a temp var just for passing it to a function.
If you want to read the whole string in:
// .str() returns a string with the contents of szBuffer
muFunc(szBuffer.str());
// Once you've taken the string out, clear it
szBuffer.str("");
If you want to extract the next line (up to the next \n character), use istream::getline:
// There are better ways to do this, but for the purposes of this
// demonstration we'll assume the lines aren't longer than 255 bytes
char buf[ 256 ];
szBuffer.getline(buf, sizeof(buf));
muFunc(buf);
getline() can also take in a delimiter as a second parameter (\n by default), so you can read it word by word.