假设我打开了这个文件(wordlist.txt):
...
14613 bore
14614 borg
14615 boric
14616 boris
14621 born
14622 borne
14623 borneo
14624 boron
...
例如,如果变量是 14623,我如何选择它旁边的单词?
如果您只执行一次,请按照 falsetru 显示的方式执行。
如果您需要查找多个数字,请将条目存储在字典中:
wordmap = {}
with open('wordlist.txt') as f:
for line in f:
key, value = line.split()
wordmap[key] = value
现在您可以像这样查找任何数字:
>>> wordmap['14623']
borneo
您可能要添加一些改进:
rstrip
单词末尾的换行符split(None, 1)
处理中间有空格的单词wordmap[int(key)]
所以你可以查找wordmap[14623]
而不是wordmap['14623']
'glassdfefewasd'
而不是转储通用异常或任何适当的。例如,这会执行 #1、#2 和 #4:
with open('wordlist.txt') as f:
wordmap = dict(line.rstrip().split(None, 1) for line in f)
尝试以下操作:
with open('wordlist.txt') as f:
for line in f:
row = line.split()
if row[0] == '14623':
print(row[1])
break
如果您只想访问该项目一次,这是非常可读的:
with open('test.txt') as f:
print next(line.split()[1] for line in f
if line.startswith('14623'))
使用正则表达式:
import re
line_num = 14615
print re.search(r''+str(line_num)+' (\w+)', file_text).group()