我希望能够从包含 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()
与 map
来创建条纹线迭代器:
with open('dictionary.txt'):
striped_lines = map(str.strip, f)
但是,如果您只想以 Python 方式计算单词数,您可以在 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)
关于Python - 将 .readlines() 与 .rstrip() 结合使用,然后将所有单词存储到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43950950/