1

所以这是一个问题:

编写一个程序来读取多行文本,并计算在 e 之前(除了 c 之后)规则 i 被破坏的单词数,以及包含 ei 或 ie 且不违反规则的单词数。

对于这个问题,我们只关心 c 是否是紧接在 ie 或 ei 之前的字符。所以科学算作违反规则,但恶作剧不会。如果一个词违反了规则两次(如 obeisancies),那么它仍然应该只计算一次。

给出的例子:

Line: The science heist succeeded
Line: challenge accepted
Line: 
Number of times the rule helped: 0
Number of times the rule was broken: 2

和我的代码:

rule = []
broken = []
line = None
while line != '':
    line = input('Line: ')

    line.replace('cie', 'broken')
    line.replace('cei', 'rule')
    line.replace('ie', 'rule')
    line.replace('ei', 'broken')

    a = line.count('rule')
    b = line.count('broken')

    rule.append(a)
    broken.append(b)

print(sum(a)); print(sum(b))

我如何修复我的代码,像问题想要的那样工作?

4

5 回答 5

1

我不会按照您的确切规范编写代码,因为这听起来像是家庭作业,但这应该会有所帮助:

import pprint

words = ['science', 'believe', 'die', 'friend', 'ceiling',
         'receipt', 'seize', 'weird', 'vein', 'foreign']

rule = {}
rule['ie'] = []
rule['ei'] = []
rule['cei'] = []
rule['cie'] = []

for word in words:
    if 'ie' in word:
        if 'cie' in word:
            rule['cie'].append(word)
        else:
            rule['ie'].append(word)
    if 'ei' in word:
        if 'cei' in word:
            rule['cei'].append(word)
        else:
            rule['ei'].append(word)

pprint.pprint(rule)

将其保存到文件中i_before_e.py并运行python i_before_e.py

{'cei': ['ceiling', 'receipt'],
 'cie': ['science'],
 'ei': ['seize', 'weird', 'vein', 'foreign'],
 'ie': ['believe', 'die', 'friend']}

您可以使用以下方法轻松计算出现次数:

for key in rule.keys():
    print "%s occured %d times." % (key, len(rule[key])) 

输出:

ei occured 4 times.
ie occured 3 times.
cie occured 1 times.
cei occured 2 times.
于 2013-08-19T09:47:41.037 回答
1

如果我理解正确,您的主要问题是每个单词都获得独特的结果。这就是你试图实现的目标:

rule_count = 0
break_count = 0
line = None
while line != '':
    line = input('Line: ')
    rule_found = False
    break_found = False

    for word in line.split():
        if 'cie' in line:
            line = line.replace('cie', '')
            break_found = True
        if 'cei' in line:
            line = line.replace('cei', '')
            rule_found = True
        if 'ie' in line:
            rule_found = True
        if 'ei' in line:
            break_found = True

        if rule_found:
            rule_count += 1
        if break_found:
            break_count += 1

print(rule_found); print(break_count)
于 2013-08-19T09:48:51.960 回答
1

首先,replace没有机会到位。您需要的是返回值:

line = 'hello there'                     # line = 'hello there'
line.replace('there','bob')              # line = 'hello there'
line = line.replace('there','bob')       # line = 'hello bob'

另外我会假设你想要实际的总数:

print('Number of times the rule helped: {0}'.format(sum(rule)))
print('Number of times the rule was broken: {0}'.format(sum(broken)))

您正在打印ab. 这些是规则在处理的最后一行中起作用和被破坏的次数。你想要总数。

作为旁注:正则表达式适用于这样的事情。re.findall会使这更加坚固和漂亮:

line = 'foo moo goo loo foobar cheese is great '
foo_matches = len(re.findall('foo', line))   # = 2
于 2013-08-19T09:36:15.963 回答
1

让我们将逻辑分解为函数,这应该有助于我们推理代码并使其正确。要遍历该行,我们可以使用以下iter函数:

def rule_applies(word):
    return 'ei' in word or 'ie' in word

def complies_with_rule(word):
    if 'cie' in word:
        return False
    if word.count('ei') > word.count('cei'):
        return False
    return True

helped_count = 0
broken_count = 0
lines = iter(lambda: input("Line: "), '')
for line in lines:
    for word in line.split():
        if rule_applies(word):
            if complies_with_rule(word):
                helped_count += 1
            else:
                broken_count += 1

print("Number of times the rule helped:", helped_count)
print("Number of times the rule was broken:", broken_count)

complies_with_rule我们可以通过缩短函数和使用生成器表达式和来使代码更简洁Counter

from collections import Counter

def rule_applies(word):
    return 'ei' in word or 'ie' in word

def complies_with_rule(word):
    return 'cie' not in word and word.count('ei') == word.count('cei')

lines = iter(lambda: input("Line: "), '')
words = (word for line in lines for word in line.split())
words_considered = (word for word in words if rule_applies(word))
did_rule_help_count = Counter(complies_with_rule(word) for word in words_considered)

print("Number of times the rule helped:", did_rule_help_count[True])
print("Number of times the rule was broken:", did_rule_help_count[False])
于 2013-08-19T12:40:36.477 回答
0
rule = []
broken = []
tb = 0
tr = 0
line = ' '
while line:
    lines = input('Line: ')
    line = lines.split()


    for word in line:

        if 'ie' in word:
            if 'cie' in word:
                tb += 1
            elif word.count('cie') > 1:
                tb += 1

            elif word.count('ie') > 1:
                tr += 1
            elif 'ie' in word:
                tr += 1

        if 'ei' in word:
            if 'cei' in word:
                tr += 1
            elif word.count('cei') > 1:
                tr += 1

            elif word.count('ei') > 1:
                tb += 1
            elif 'ei' in word:
                tb += 1




print('Number of times the rule helped: {0}'.format(tr))
print('Number of times the rule was broken: {0}'.format(tb))

完毕。

于 2013-08-19T11:26:26.820 回答