[英]Append lines from a text file to a list in python without '\n'
[英]How to append lines from file into a list while keeping the number of lines - python 3
我试图从包含约90000行的文件中提取单词(每行包含3到数百个单词。我想在提取单词后将这些行追加到列表中。我能够将提取的单词插入到列表中,其中包含一行内容。我想在保留90000行内容的同时将单词插入列表中,有什么想法吗?
clean_sentence = [],其中open(folder_path + text_file_name,'r',encoding ='utf-8')为f:
for line in f:
sentence = line.split()
for word in sentence:
if word.endswith('er'):
clean_sentence.append(word[:-2])
else:
clean_sentence.append(word)
x = ' '.join(clean_sentence)
with open('StemmingOutFile.txt','w', encoding="utf8") as StemmingOutFile:
StemmingOutFile.write(x)
该文件不是英语,但以下示例说明了当前的问题:当前代码产生:
why don't you like to watch TV? are there any more fruits? why not?
我希望输出文件为:
why don't you like to watch TV?
are there any more fruits?
why not?
逐行读取文件:
with open('file.txt','r') as f:
lines = f.read().splitlines()
然后进行阻止:
new_lines = []
for line in lines:
new_lines.append(' '.join[stemmed(word) for word in line])
其中stemmed
的功能如下:
def stemmed(word):
return word[:-2] if word.endswith('er') else word
然后将每行new_lines
写入StemmingOutFile.txt中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.