字数用Python中的模式

时间:2013-08-19 09:28:27

标签: python python-3.x

所以这就是问题:

  

编写程序以读取多行文本并计算数字   e之前的规则i除了c之后被破坏的时候   包含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))

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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.

答案 2 :(得分: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)

答案 3 :(得分: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])

答案 4 :(得分: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))

完成。