0

How do you check for lines with N number of periods in them?

my_count = 6
indict = open("dictionary.txt").read().splitlines()
for line in indict:
# if line has my_count num of '.':
    print line

dictionary.txt looks like:
A.BAN.DON
A.BOUND
A.BI.DING

Appreciate any help!

user1899415
  • 3,015
  • 7
  • 22
  • 31
  • See http://stackoverflow.com/questions/1155617/count-occurrence-of-a-character-in-a-python-string – aqua Mar 05 '13 at 03:30
  • Are there sentences? Do you only count words with periods? What about standalone? What about at the end of sentences? – dawg Mar 05 '13 at 04:25

2 Answers2

3

Use the count function.

my_count = 6
indict = open("dictionary.txt").read().splitlines()
for line in indict:
    # if line has my_count num of '.':
    if line.count('.') == my_count:
        print line
Tyler Ferraro
  • 3,753
  • 1
  • 21
  • 28
0

EDIT: Or well — look at the way described by @Tyler Ferraro.

The question is how do you define a line in your language? A line must end with a period. So technically a line can only contain 0 or 1 periods depending on who you ask.

If it's contained in '' like: '.' or "" like ".", then it's a different case and you could use regex.

I am assuming your line is like: A.BAN.DON

for line in indict:
# if line has my_count num of '.':
    for character in line:
        if character is ".":
            dotCount += 1
    print "line: %s has %d periods" % (line, dotCount)

And you can arrange the rest of the stuff yourself (like declaring dotCount, etc...)

p0lAris
  • 4,750
  • 8
  • 45
  • 80