[英]AttributeError: '_io.TextIOWrapper' object has no attribute 'lower' for txt file
Here is my code (A pig Latin translator from a text file):这是我的代码(来自文本文件的猪拉丁语翻译器):
f = open('Assignment_4.txt', 'r+')
for line in f:
print(line)
def pigLatin():
var = 'ay'
wordL = f.lower()
firstLetter = wordL[0]
pigLatin = wordL + firstLetter + var
pigLatin = pigLatin[1:]
print(pigLatin)
It works for defined strings but won't for the file.它适用于定义的字符串,但不适用于文件。 Help is appreciated!
帮助表示赞赏!
Points:积分:
lower()
works with string. lower()
适用于字符串。 You are trying to use with file handle f
.f
一起使用。 That's why you are getting this error.pigLatin()
for each line as pigLatin(line)
.pigLatin()
为pigLatin(line)
。 So, now , pigLatin() function expects one argument.f.close()
.f.close()
。 It will be if you use with
statement to open file.with
语句打开文件,它将是。 Code with comments inline:带有内联注释的代码:
def pigLatin(stuff_to_be_changed):
var = 'ay'
wordL = stuff_to_be_changed.lower()
firstLetter = wordL[0]
pigLatin = wordL + firstLetter + var
pigLatin = pigLatin[1:]
print(pigLatin)
#For string
string = "I am to change"
#Call function
pigLatin(string)
f = open('Assignment_4.txt', 'r+')
#For file
for line in f:
print(line)
#Call function
pigLatin(line)
#Close the file
f.close()
The error is quite right - file objects don't have a lower()
method - before you can use your function you need to read
a line of text from your file and split
it into separate words.错误是正确的 - 文件对象没有
lower()
方法 - 在您可以使用您的函数之前,您需要从文件中read
一行文本并将其split
为单独的单词。 (Note that it is never a good idea to use the same name for a variable and a method as it can cause confusion.) (请注意,对变量和方法使用相同的名称从来都不是一个好主意,因为这会导致混淆。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.