【问题标题】:Counting articles from 3 sentences从 3 个句子计算文章
【发布时间】:2015-09-26 19:05:02
【问题描述】:
计算定冠词和不定冠词
这就是我现在所拥有的。我是新手,我想我必须对数组做点什么?所以我的第一个问题是如何将输入变成一个列表。
import sys
def main():
indefinite = 0
definite = 0
article = ""
for line in sys.stdin:
line = line.strip()
for word in line.split():
if article == 'een' in line:
indefinite = indefinite + 1
if article == 'het' in line:
definite = definite + 1
if article == 'de' in line:
definite = definite + 1
print(indefinite)
print(definite)
main()
【问题讨论】:
标签:
python
arrays
string
list
count
【解决方案1】:
您的if 语句是错误的,因为您没有使用for 变量word,它应该是if word=='xxx':,或者更好的是您可以跳过所有if 语句并使用indefinite+=(word=='een') 和@987654326 @ 使用 True 为 1 而 False 为 0 的事实
在您的程序更“Pythonic”版本的下方(我的代码是 Python 2.7,需要稍作转换才能在 Python 3 中工作):
import re, itertools, sys
def main():
indefinite = 0
definite = 0
for line in sys.stdin:
# regular expression to find articles in line
# match is a list with all the articles found
match=re.findall(r"\been|de|het\b",line,re.I)
# list compreension to create an articles dictionary
# itertools.groupby make an iterator that returns consecutive keys and groups from the iterable.
articles={k: len(list(g)) for k,g in itertools.groupby(match)}
# count definite/indefinite articles
for k in articles.keys():
if k in ['het','de']:
definite+=articles[k]
else:
indefinite+=articles[k]
print "%d definite articles, %d indefinite articles" % (definite, indefinite)
main()