python:检查包含X个句点'.'的行

0 投票
2 回答
1778 浏览
提问于 2025-04-17 17:57

你怎么检查一行里面有多少个句号(.)呢?

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

感谢任何帮助!

2 个回答

0

编辑:或者说——看看@Tyler Ferraro描述的方式。

问题是你在你的编程语言中如何定义一行?一行必须以句号结束。所以从技术上讲,一行只能包含0个或1个句号,这要看你问谁。

如果句号被包含在''里,比如说'.',或者在""里,比如说".",那就是另一种情况,你可以使用正则表达式来处理。

我在这里假设你的一行是这样的: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)

然后你可以自己安排其他的内容(比如声明dotCount等等...)

3

使用计数函数。

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

撰写回答