[英]Python Take raw input and search for it in a line with multiple characters
我正在尝试在特定点的字符串中搜索用户定义的一组特定字符。 到目前为止,这是我的代码:
# -*- coding: utf-8 -*-
f = open("text.txt", 'r')
linelist = f.readlines()
f.close
User_number = raw_input('What number would you like to single
out from your text?')
anum1 = User_number[0]
anum2 = User_number[1]
f4 = open("Modded_text.txt", "w")
for line in linelist:
i =0;
if anum1 in line[10] and anum2 in line[11]:
f4.write(line)
f4.close()
我的问题是,这给了我“ IndexError:字符串索引超出范围”。 即使它确实可行,这似乎也是我想要做的一团糟。 谁能为我提供建议,让我知道如何使它起作用并改善我的代码?
您尚未发布追溯,但是我猜这里发生了超出范围的错误:
if anum1 in line[10] and anum2 in line[11]:
这是因为代码假定文件中的每一行至少有12个字符长。 您的输入文件中可能有一个空行,最有可能在结尾处,这是零个字符。 删除此行: i =0;
(它没有做任何有用的事情),并将其放在下面:
if len(line) < 12:
continue
这样可以确保数据符合您的代码期望。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.