如何计算以字符串开头的单词数

War*_*mot 3 python loops list while-loop python-2.7

我正在尝试编写一个计算前缀、后缀和根的代码。我需要知道的是如何计算以特定字符串(例如“co”)开头或结尾的单词数。

这就是我到目前为止所拥有的。

SWL=open('mediumWordList.txt').readlines()
  for x in SWL:
      x.lower
      if x.startswith('co'):
          a=x.count(x)
while a==True:
    a=+1
    print a
Run Code Online (Sandbox Code Playgroud)

我从中得到的只是一个无限循环。

Kas*_*mvd 5

首先,作为处理文件的更Pythonic的方式,您可以使用with语句打开文件,该文件会在块末尾自动关闭文件。

此外,您不需要使用readlines方法来加载内存中的所有行,您可以简单地循环文件对象。

关于计算单词数,您需要将行拆分为单词,然后使用str.stratswithstr.endswith根据您的条件计算单词数。

因此,您可以在函数中使用生成器表达式sum来计算单词数:

with open('mediumWordList.txt') as f:
   sum(1 for line in f for word in line.split() if word.startswith('co'))
Run Code Online (Sandbox Code Playgroud)

请注意,我们需要拆分行才能访问单词,如果不拆分行,您将循环遍历该行的所有字符。

正如评论中所建议的,作为一种更Pythonic的方式,您可以使用以下方法:

with open('mediumWordList.txt') as f:
   sum(word.startswith('co') for line in f for word in line.split())
Run Code Online (Sandbox Code Playgroud)