如何在python中将文本文件拆分为单词?
我对python非常陌生,之前也无法使用文本…我有100个文本文件,每个文件都有约100至150行非结构化文本来描述患者的状况。我使用以下命令在python中读取了一个文件:
with open("C:\\...\\...\\...\\record-13.txt") as f:
content = f.readlines()
print (content)
现在,我可以使用以下方式将该文件的每一行拆分为单词:
a = content[0].split()
print (a)
但是我不知道如何将整个文件分割成单词?循环(同时或针对)对此有帮助吗?
谢谢您的帮助。您的答案可帮助我编写此代码(在我的文件中,单词按空格分隔,所以我认为是定界符!):
with open ("C:\\...\\...\\...\\record-13.txt") as f:
lines = f.readlines()
for line in lines:
words = line.split()
for word in words:
print (word)
只是按行分割单词(一行中一个单词)。
-
没有人建议过发电机,我很惊讶。这是我的处理方式:
def words(stringIterable): #upcast the argument to an iterator, if it's an iterator already, it stays the same lineStream = iter(stringIterable) for line in lineStream: #enumerate the lines for word in line.split(): #further break them down yield word
现在,这可以在您可能已经在内存中的简单句子列表中使用:
listOfLines = ['hi there', 'how are you'] for word in words(listOfLines): print(word)
但是它在文件上也可以正常工作,而无需读取内存中的整个文件:
with open('words.py', 'r') as myself: for word in words(myself): print(word)