如何解决seek() 函数在嵌套循环中不起作用
我正在为缩写构建自定义“翻译器”。它应该接受一个字符串输入,将其拆分为单个单词并将每个单词作为缩写返回。
示例:
Input: above and aloft
Returns: abv & alft
缩写是从 txt 文件中检索的,其中缩写和关键短语由制表符分隔。每一对都在单独的行上。
import csv
# Used to lowercase the library
file = open('lib.txt','r')
lines = [line.lower() for line in file]
with open('lib.txt','w') as out:
out.writelines(sorted(lines))
# Get user input
eng = input("Plain english input:")
# Split input into separate words
words = eng.split()
# Search every word in the file,return the first word (abbreviation) in the respective line
with open('lib.txt',newline='') as lib:
lib_reader = csv.reader(lib,delimiter='\t')
lib.seek(0)
print(words)
for x in words:
print('1')
lib.seek(0)
for lib in lib_reader:
print('2')
if x in lib:
print(lib[0])
break
无论出于何种原因,它运行良好,找到第一个单词,中断,返回到第一个循环并在 lib.seek(0) 上给出错误。
AttributeError: 'list' object has no attribute 'seek'
据我所知,它必须将光标重置到文件中文本的开头,以便重新开始搜索第二个单词。 seek() 是为了防止它退出循环并继续搜索下一个参数。
解决方法
我想也许您在两件事上使用了相同的变量。该冲突将 lib
文件句柄替换为 lib
来自 csv 阅读器的行,该行是一个列表。这就是您收到该错误的原因,因为该列表没有 seek
方法。
对于从 lib_row
读取的每一行,尝试使用 lib
而不是 lib_reader
。
Python 没有块作用域,因此 for
循环中的变量与函数中的变量相同。
for lib_row in lib_reader:
print('2')
if x in lib_row:
print(lib_row[0])
break
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。