Can someone please help convert the following C++ method into Python? //Method t
ID: 3740568 • Letter: C
Question
Can someone please help convert the following C++ method into Python?
//Method to be called when program runs to read files one by one and add to inverted index
void getFilesToBeRead() {
string str;
ifstream in("File.txt");
while (getline(in, str)) {
ifstream file(str);
string word;
int position{ 0 };
char c;
int wordCount = 0;
while (file.get(c)) { // loop to get characters one by one
if ((c > 64 && c < 91) || (c > 96 && c < 123)||(c > 47 && c < 58)) {//ascii values used to ignore punctuation marks in text input
word += tolower(c);
}
else {
++position;
addWordToIndex(word, str, position);
word = "";//re-initializing to empty string to get next word
}
}
position = 0;//re-initializing to get positions from next document
}
}
Explanation / Answer
#!/usr/bin/python
def getFilesToBeRead():
str=""
fo = open("File.txt","r")
while(str in fo):
str=fo.read(20)
word=""
position=0
c=''
wordCount=0
while(c=fo.read(1)):
c=ord(fo.read(1))
if ((c > 64 and c < 91) or (c > 96 and c < 123) or (c > 47 and c < 58)): #ascii values used to ignore punctuation marks in text input
word += c.lower()
else:
position=position+1
addWordToIndex(word, str, position)
word = "" #re-initializing to empty string to get next word
return