我正在尝试读取一个文本文件,并在新文件中将该文件的内容转换为pig latin。这就是我所拥有的:
def pl_line(word):
statement = input('enter a string: ')
words = statement.split()
for word in words:
if len(word) <= 1:
print(word + 'ay')
else:
print(word[1:] + word[0] + 'ay')
def pl_file(old_file, new_file):
old_file = input('enter the file you want to read from: ')
new_file = input('enter the file you would like to write to: ')
write_to = open(new_file, 'w')
read_from = open(old_file, 'r')
lines = read_from.readlines()
for line in lines():
line = pl_line(line.strip('\n'))
write_to.write(line + '\n')
read_from.close()
write_to.close()
但是,当我运行它时,我收到以下错误消息: TypeError:'list'对象不可调用
有关如何改进代码的任何想法?
答案 0 :(得分:2)
以下是对实际转换器的一些改进:
_VOWELS = 'aeiou'
_VOWELS_Y = _VOWELS + 'y'
_SILENT_H_WORDS = "hour honest honor heir herb".split()
def igpay_atinlay(word:str, with_vowel:str='yay'):
is_title = False
if word.title() == word:
is_title = True
word = word.lower()
# Default case, strangely, is 'in-yay'
result = word + with_vowel
if not word[0] in _VOWELS and not word in _SILENT_H_WORDS:
for pos in range(1, len(word)):
if word[pos] in _VOWELS:
result = word[pos:] + word[0:pos] + 'ay'
break
if is_title:
result = result.title()
return result
def line_to_pl(line:str, with_vowel:str='yay'):
new_line = ''
start = None
for pos in range(0, len(line)):
if line[pos].isalpha() or line[pos] == "'" or line[pos] == "-":
if start is None:
start = pos
else:
if start is not None:
new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel)
start = None
new_line += line[pos]
if start is not None:
new_line += igpay_atinlay(line[start:pos], with_vowel=with_vowel)
start = None
return new_line
tests = """
Now is the time for all good men to come to the aid of their party!
Onward, Christian soldiers!
A horse! My kingdom for a horse!
Ng!
Run away!
This is it.
Help, I need somebody.
Oh, my!
Dr. Livingston, I presume?
"""
for t in tests.split("\n"):
if t:
print(t)
print(line_to_pl(t))
答案 1 :(得分:0)
您很可能将作业混淆为read_from
和write_to
,因此您无意中尝试从仅为写入权限打开的文件中读取。