更新:我当前的问题是如何让我的代码从每个新搜索短语开始读取到 EOF。
这是我正在做的一项任务,目前一直在坚持。请注意,这是使用 Python 的初学者编程类(class)。
jargon = open("jargonFile.txt","r")
searchPhrase = raw_input("Enter the search phrase: ")
while searchPhrase != "":
result = jargon.readline().find(searchPhrase)
if result == -1:
print "Cannot find this term."
else:
print result
searchPhrase = raw_input("Enter the search phrase: ")
jargon.close()
任务是获取用户的 searchPhrase 并在文件 (jargonFile.txt) 中找到它,然后让它打印结果(这是它出现的行和出现的字符)。我将使用一个计数器来查找发生的行号,但我将在稍后实现它。现在我的问题是我得到的错误。我找不到搜索整个文件的方法。
示例运行:
Enter the search phrase: dog
16
Enter the search phrase: hack
Cannot find this term.
Enter the search phrase:
“dog”出现在第一行,但它也出现在 jargonFile 的其他行(多次作为字符串),但它仅显示第一行中的第一次出现。在 jargonFile 中多次发现字符串 hack,但我的代码设置为仅搜索第一行。我该如何解决这个问题?
如果这还不够清楚,我可以在需要时发布作业。
最佳答案
首先打开文件并使用 readline() 将其读入字符串。稍后您尝试从第一步中获得的字符串中读取 readline()。
你需要注意你正在处理的对象(东西):open() 给你一个文件“jargon”,readline on jargon 给你字符串“jargonFile”。
所以 jargonFile.readline 不再有意义了
更新为对评论的回答:
好了,既然str错误问题解决了,再想想程序结构:
big loop
enter a search term
open file
inner loop
read a line
print result if string found
close file
您需要更改您的程序以使其遵循该描述
更新二:
SD,如果你想避免重新打开文件,你仍然需要两个循环,但这次一个循环将文件读入内存,完成后第二个循环要求搜索词。所以你会像这样构造它
create empty list
open file
read loop:
read a line from the file
append the file to the list
close file
query loop:
ask the user for input
for each line in the array:
print result if string found
要获得教授的额外加分,请在您的解决方案中添加一些评论,提及两种可能的解决方案,并说明您选择的原因。提示:在这种情况下,这是执行时间(内存很快)和内存使用量(如果您的行话文件包含 1 亿个条目怎么办……好吧,在那种情况下您会使用比平面文件更复杂的东西, 但你也不能将它加载到内存中。)
哦,对第二种解决方案还有一个提示:Python 支持元组 ("a","b","c") 和列表 ["a","b","c"]。你想使用后者,因为列表可以修改(元组不能。)
myList = ["Hello", "SD"]
myList.append("How are you?")
foreach line in myList:
print line
==>
Hello
SD
How are you?
好的,最后一个例子包含了你程序的第二个解决方案的所有新内容(定义列表、追加到列表、遍历列表)。享受将它们组合在一起的乐趣。
关于python - 属性错误 : 'str' object has no attribute 'readline' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/596886/