因此,通过使用'for'语句,我将文本文件分解为列表:
['these', 'are', 'lines']
['meant', 'to', 'be', 'translated']
['to', 'piglatin']
所以基本上如果以元音“aeiou”开头,你会接受+'yay'这个词,如果它没有你将字母移到后面直到你到达元音然后添加yay,如果它没有你忽略它的元音。
例如;即将翻译,将是:aboutyay otay ebay anslatedtray。
到目前为止,这是我的代码:
untranslated = open('english.txt','r')
vowels = 'aeiou'
for lines in untranslated:
words = lines.split()
print(words)
我不想要完整的代码如何完成这个或多或少我将从第一个单词开始以及如何拼接它。
答案 0 :(得分:0)
如何切割字符串:
word = 'these'
print word[0] # it's similar to list indexing, starts at 0
要按顺序获取字母,请使用负数:word[-1]
是最后一个字母; word[-2]
是倒数第二个等等。
word[1:]
返回索引1(第二个字母)到结尾的每个字母。
'word [:5] returns every letter up to index 5 (exclusive, letters 1, 2, 3, and 4).
words [1:5]`返回索引1到索引5(字母2,3和4)的每个字母。
由于你有多行,你想要words += lines.split()
,因为
untranslated = open('english.txt','r')
vowels = ('a', 'e', 'i', 'o', 'u') # I like using lists/tuples rather than strings
# if you are just checking if something is in it
newWords = []
for lines in untranslated:
words += lines.split() # this fixes the last line problem
# this assumes each word is on one line, separated by a space (like: 'these are words')
for word in words: # iterates through every word
if word[0] in vowels: # if first letter is a vowel
new_word = word + 'yay'
else:
new_word = word[1:] + word[0] + 'ay'
newWords.apend(new_word)
根据Eric Roper的建议,您可以创建字典作为翻译:
newWords = {}
for word in words:
if word[0] in vowels:
new_word = word + 'yay'
newWords[word] = new_word
else:
new_word = word[1:] + word[0] + 'ay'
newWords[word] = new_word
一些参考文献: