简体   繁体   English

计算表格中的单词总数

[英]Counting total number of words in a table

If i have a text file, containing: 如果我有一个文本文件,包含:

Alex is a footballer
Alex loves football

and after reading the text file into a list in python, it outputs: 在将文本文件读入python列表后,输出:

lst = [['Alex','is','a','footballer'],['Alex','loves','football']]

How do i count the number of words in the list? 如何计算列表中的单词数? I'm thinking of something like: 我在想类似的东西:

count = 0
for word in lst:
    count += len(lst)

Output: 输出:

Total number of words: 7

You can also do sum(map(len,lst)) . 您也可以执行sum(map(len,lst)) More concise. 更简洁。

That works correctly if you want it to make more sense replace word with line. 如果您希望更有意义,则可以用行替换单词。 This is because list contains a list of lists(these smaller lists are one line of the text file). 这是因为list包含一个列表列表(这些较小的列表是文本文件的一行)。

Also if you don't want to do it in the python code, in terminal you can just write wc -w file.txt to see the number of words in that file. 同样,如果您不想在python代码中执行此操作,则在终端中,您只需编写wc -w file.txt即可查看该文件中的单词数。

Another canonical way is to use itertools.chain.from_iterable and sum 1 from each element. 另一种规范的方法是使用itertools.chain.from_iterable并对每个元素求和1

import itertools

result = sum(1 for _ in itertools.chain.from_iterable(lst))
# equivalent to sum(1 for sublst in lst for el in sublst)

but your example code is fine. 但是您的示例代码很好。

您可以在一行中完成此操作:

total = sum([len(i) for i in lst])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM