【问题标题】:How to count number of words that start with a string如何计算以字符串开头的单词数
【发布时间】:2016-01-13 22:47:01
【问题描述】:

我正在尝试编写一个计算前缀、后缀和根的代码。 我只需要知道如何计算以某个字符串(例如“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

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

【问题讨论】:

  • 嗯......你有while True循环,它永远不会转向False因此infinite
  • 一般代码注释:x.lower 本身是一个空操作;它查找str.lower 方法,然后什么也不做。你想要x = x.lower()(括号实际上调用lower,并且你必须分配回x,因为x.lower()返回一个新字符串,它不会改变str的位置(Python的str是不可变的,没有任何改变)。另外,a=+1 在语法上是合法的,但它的意思是a = (+1)(相当于a = 1);你可能是指a += 1)。

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


【解决方案1】:

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

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

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

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

【讨论】:

  • 另一种方法是避免在生成器表达式中进行过滤; True 是 1,False 在数字上是 0,所以你可以这样做:sum(word.startswith('co') for line in f for word in line.split()) 使用 startswith 直接检查的结果。两者都不是天生优越的,只是为了完整性而提及它。
  • @ShadowRanger 确实忘记了,感谢改进!
  • 这很棒!我仍然有剥离和降低列表的问题。知道我该怎么做吗?非常感谢!
【解决方案2】:

您可以尝试使用集合中的 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']

【讨论】:

  • 如何修改该代码以从“mediumWordList.txt”中计算“co”
  • from collections import Counter with open('mediumWordList.txt') as barF: words = [word for line in barF.readlines() for word in line.split()] c = Counter(words ) NumberOfCOWords = c['co']
猜你喜欢
  • 2023-02-21
  • 1970-01-01
  • 2021-03-12
  • 2018-09-03
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多