def main():
pigFile = open('pigTest.txt', 'r')
pigOut = open('pigOut.txt', 'w')
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
pigList = getWords(vowels, pigFile)
t = translate(pigList, vowels)
print(pigList)
print("Converted: ", t)
w = write(t, pigOut)
pigFile.close()
def getWords(vowels, file):
data = file.read().split()
return data
def translate(pigList, vowels):
newPigList = []
for word in pigList:
if word[0] in vowels: # if the first index of the first word is a vowel
newPigList.append(word + "way") #add to new list
else: #if letter does not begin with vowel
newPigList.append(word[1:] + word[0] + "ay")
return newPigList
def write(pigList, pigOut):
pigOut.write(" ".join(pigList))
main()
输出:
['if', 'beast', 'student', 'away']
Converted: ['ifway', 'eastbay', 'tudentsay', 'awayway']
问题:'远离'应该在输出的新行上,因为在pigTest.txt中它在新行上
我的程序将所有文本推送到第一行,当它应该放在正确的行上时,我不知道如何解决它
我的txt文件看起来像这样
if beast student
away
答案 0 :(得分:0)
解决方案是逐行处理输入。一种方法是调用pigFile.readlines()
并迭代它返回的行。
def main():
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
pigFile = open('pigTest.txt', 'r')
pigOut = open('pigOut.txt', 'w')
for line in pigFile.readlines():
pigList = line.split()
t = translate(pigList, vowels)
print("Input: ", pigList)
print("Converted: ", t)
w = write(t, pigOut)
pigFile.close()
def translate(pigList, vowels):
newPigList = []
for word in pigList:
if word[0] in vowels: # if the first index of the first word is a vowel
newPigList.append(word + "way") #add to new list
else: #if letter does not begin with vowel
newPigList.append(word[1:] + word[0] + "ay")
return newPigList
def write(pigList, pigOut):
pigOut.write(" ".join(pigList))
main()
答案 1 :(得分:0)
确保您了解str.join
docs
你想要:
"\n".join(pigList)
答案 2 :(得分:-1)
尝试这种方式: -
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
with open('file2.txt') as f, open('pigOut.txt', 'w+') as out:
newPigList = []
for line in f.read().splitlines():
line = line.split()
newPigList.append(map(lambda x: x+'way' if x[0] in vowels else x[1:] + x[0] + "ay", line))
print newPigList
for data in newPigList:
out.write(str(data)+'\n')
out.seek(0)
print out.read()
输出: -
[['ifway', 'eastbay', 'tudentsay'], ['awayway']]
['ifway', 'eastbay', 'tudentsay']
['awayway']