python - 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
推荐阅读
- python - 根据条件替换合并数据框中的 NaN --(Python,Pandas)
- javascript - 在 JSX 中映射第二个数组
- html - 如何进行交互式 HTML 启动
- unit-testing - kotlin + Spring boot 中的单元测试休息控制器
- javascript - symfony 4 - 如何在 5 秒后清除 Flash 消息?
- c++ - 覆盖在具有子类的基类中定义的函数
- mysql - WITH ROLLUP 和 DISTINCT 问题的错误使用
- java - Spring Boot - 无法查看带有控制器和配置设置的网页
- php - 当我尝试它时,php 中的 Preg_match 无法正常工作
- python - 将 Eye Gaze(俯仰和偏航)转换为屏幕坐标(人在看哪里?)