0

到目前为止我的代码:

untranslated = open('english.txt','r')
vowels = ('a','e','i','o','u')
newWords = []

for lines in untranslated:
    words = lines.split()
    for word in words:
        if word[0] in vowels:
            word = word + 'yay'
        else:
            while word[0] not in vowels:
                word = word[1:] + word[0]
            word = word + 'ay'
        print(word)

English.txt 文件的内容:

these are lines
meant to be translated
to piglatin

到目前为止,我已经翻译了所有单词,但我的问题是它没有返回到与输入相同的行。

我希望最终结果看起来像:

esethay areyay ineslay
eantmay otay ebay anslatedtray
otay iglatinpay

我该怎么做呢?

我得到的是:

esethay
areyay
ineslay
eantmay
otay
ebay
anslatedtray
otay
iglatinpay
4

2 回答 2

1

我建议先列一个列表,然后再打印元素。

for lines in untranslated:
    latin = []
    words = lines.split()
    for word in words:
        if word[0] in vowels:
            word = word + 'yay'
        else:
            while word[0] not in vowels:
                word = word[1:] + word[0]
            word = word + 'ay'
        latin.append(word)
    print(' '.join(latin))

这将在每一行创建一个新列表。结果单词被附加到列表中,然后我们用 a 连接单词' '并打印它们。

于 2013-02-23T03:00:54.677 回答
0

您每行打印一个单词。如果你想每行打印一个句子,你可以使用join

pl_words = []

for word in words:
   ...
   pl_words.append(word)

print(' '.join(pl_words))

end关键字参数print

    print(word, end=' ')

print()  # To make a new line

不过,我会用正则表达式来做:

import re

words = '''
    these are lines
    meant to be translated
    to piglatin
'''

vowels = 'aeiou'

def pig_latinize(word):
    if word[0] in vowels:
        return word + 'yay'

    while word[0] not in vowels:
        word = word[1:] + word[0]

    return word + 'ay'

def replacer(match):
    return pig_latinize(match.group())

print(re.sub(r'(\w+)', replacer, words))
于 2013-02-23T03:01:48.477 回答