Python - 使用 .readlines() 和 .rstrip() 然后将所有单词存储到列表中

Python - Using .readlines() with .rstrip() and then store all words into a list

我希望能够从包含 120,000 多个单词的文本文件 (dictionary.txt) 中删除 \n 字符 ( .rstrip('\n') )。然后计算每一行和 returns txt 文件中的单词数量(每个单词在其自己的行上)。 然后最后想要将所有单词存储到列表中。

目前,下面的代码 returns 行数但不删除 \n 字符,因此它可以存储到列表中。

 def lines_count():
        with open('dictionary.txt') as file:
            print (len(file.readlines()))

如果你想要没有尾随换行符的行列表,你可以使用 str.splitlines() 方法,在这种情况下你可以使用 file_obj.read() 将文件读取为字符串,然后使用 splitlines() 在整个字符串上。虽然,当 open 函数已经从您的行中返回一个生成器时,不需要这样的事情(您可以在处理行时简单地删除尾随的换行符)或者只调用 str.strip() a map 创建条纹迭代器:

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)

如果你想 return 没有 \n 的行列表,然后打印这个列表的长度:

def line_list(fname):
    with open(fname) as file:
        return file.read().splitlines()

word_list = line_list('dictionary.txt')  # 1 word per line
print(len(word_list))