计算确定和不定的文章
这就是我现在所拥有的。我是新手,我想我必须对数组做些什么?所以我的第一个问题是如何将输入转换为列表。
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()
答案 0 :(得分:0)
您的if
语句错误,因为您没有使用for
变量word
,它应该是if word=='xxx':
甚至更好,您可以跳过所有if语句并使用indefinite+=(word=='een')
和definite+=(word=='het') or (word=='de')
使用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()