简体   繁体   中英

How to count number of words that start with a string

I'm trying to write a code that counts prefix's,suffix's, and roots. All I need to know is how to count the numbers of words that start or end with a certain string such as 'co'.

this is what I have so far.

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

all I get from this is an infinite loop of ones.

First of all as a more pythonic way for dealing with files you can use with statement to open the file which close the file automatically at the end of the block.

Also you don't need to use readlines method to load all the line in memory you can simply loop over the file object.

And about the counting the words you need to split your lines to words then use str.stratswith and str.endswith to count the words based on your conditions.

So you can use a generator expression within sum function to count the number of your words :

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

Note that we need to split the line to access the words, if you don't split the lines you'll loop over the all characters of the line.

As suggested in comments as a more pythonic way you can use following approach :

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

You could try to use Counter class from collections. For example, to count 'Foo' in Bar.txt:

    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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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