我只想逐行从文件中读取,并将每一行附加到数组中。我以前做过,没有任何问题,我不知道为什么这一次它不工作!打印函数只显示文件的第一行!!这是我的代码:
keyword_array = []
with open('local directory\\C0577785c.txt') as my_keywordfile:
for keyword in my_keywordfile.readline().strip("[]").strip("'").split(","):
keyword_array.append( keyword.strip().strip("'").lower())
print(keyword_array)另外,以下是文件内容的子集:
C0001396 adam attack stokes
C0001396 Adam Stokes Attacks
C0001396 Adam-Stokes Attacks
C0001396 adam-stokes syndrome
C0001396 adams attack stoke
C0001396 adams stoke syndrome
C0001396 adams stokes attack
C0001396 ADAMS STOKES SYNDROME
C0001396 Adams-Stokes
C0001396 Adams-Stokes Syndrome
C0001396 Adams-Stokes; attack
C0001396 attack; Adams-Stokes
C0001396 attack; Stokes-Adams
C0001396 Attacks, Adam-Stokes
C0001396 Attacks, Stokes-Adams
C0001396 morgagni's disease
C0001396 Morgagni-Adam's Stokes syndrome
C0001396 Morgagni-Stokes-Adams谢谢,
发布于 2017-09-21 01:15:58
使用嵌套循环读取my_keywordfile的行。
for line in my_keywordfile.readlines():
for keyword in line.strip("[]").strip("'").split(","):发布于 2017-09-21 01:14:32
您只调用readline()一次,因此只打印一行。
发布于 2017-09-21 01:15:19
在for循环中,要调用文件对象上的.readlines()。不是读行()。readline()只返回第一行,readline()返回可以迭代的行列表。
从医生那里:
readlines(...) method of _io.TextIOWrapper instance
Return a list of lines from the stream.
hint can be specified to control the number of lines read: no more
lines will be read if the total size (in bytes/characters) of all
lines so far exceeds hint.我还建议不要清理for循环声明中的行。它认为,如果在for循环中这样做,读起来会容易一些。
# ....
with open('myfile.txt', 'r') as my_file:
for raw_line in my_file.readlines():
cleaned_data = raw_line.lower().strip("'")
#....https://stackoverflow.com/questions/46333874
复制相似问题