我希望能够从包含 120,000 多个单词的文本文件 (dictionary.txt) 中去除 \n 字符( .rstrip('\n') )。然后计算每一行并返回 txt 文件中的单词数量(每个单词在自己的行上)。然后最后希望将所有单词存储到列表中。
目前,下面的代码返回行数,但不会去除 \n 字符,因此可以将其存储到列表中。
def lines_count():
with open('dictionary.txt') as file:
print (len(file.readlines()))
如果您想要没有尾随换行符的行列表,您可以使用str.splitlines()
方法,在这种情况下,您可以将文件作为字符串读取,file_obj.read()
然后使用splitlines()
整个字符串。虽然,当open
函数已经从你的行中返回一个生成器时,不需要这样的事情(你可以在处理行时简单地去除尾随的换行符)或者只调用str.strip()
with amap
来创建一个带条线的迭代器:
with open('dictionary.txt'):
striped_lines = map(str.strip, f)
但是,如果您只想将单词数作为 Pythonic 的方式,您可以在sum
函数中使用生成器表达式,如下所示:
with open('dictionary.txt') as f:
word_count = sum(len(line.split()) for line in f)
请注意,在拆分行时无需剥离新行。
例如
In [14]: 'sd f\n'.split()
Out[14]: ['sd', 'f']
但是如果你仍然想要列表中的所有单词,你可以使用列表理解而不是生成器表达式:
with open('dictionary.txt') as f:
all_words = [word for line in f for word in line.split()]
word_count = len(all_words)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句