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

时间:2015-10-15 12:56:12

标签: python list python-2.7 loops while-loop

我正在尝试编写一个代码,用于计算前缀,后缀&和根。 我需要知道的是如何计算以某个字符串开头或结尾的单词数,例如' 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

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

2 个答案:

答案 0 :(得分:4)

首先,作为处理文件的更加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'))

请注意,我们需要拆分该行以访问这些字词,如果您不拆分这些字符,则会循环显示该行的所有字符。

正如评论中建议的那样,您可以使用以下方法:

with open('mediumWordList.txt') as f:
   sum(word.startswith('co') for line in f for word in line.split())

答案 1 :(得分:1)

您可以尝试从集合中使用Counter类。例如,要计算Bar.txt中的'Foo':

    from collections import Counter
    with open('Bar.txt') as barF:
      words = [word for line in barF.readlines() for word in line.split()]
    c = Counter(words)
    print c['Foo']
相关问题