Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python获取原始输入并在包含多个字符的行中搜索它_Python - Fatal编程技术网

Python获取原始输入并在包含多个字符的行中搜索它

Python获取原始输入并在包含多个字符的行中搜索它,python,Python,我试图在字符串中的特定点搜索用户定义的特定字符集。这是我目前的代码: # -*- 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]

我试图在字符串中的特定点搜索用户定义的特定字符集。这是我目前的代码:

# -*- 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()  

我的问题是,这给了我“索引器错误:字符串索引超出范围”。这似乎也是一个混乱的方式做我想要的,即使它确实工作。有谁能给我一些建议,告诉我如何才能让它工作并改进我的代码吗?

您还没有发布回溯,但我猜您的越界错误发生在这里:

if anum1 in line[10] and anum2 in line[11]:
这是因为代码假定文件中的每一行至少有12个字符长。输入文件中可能有一个空行,最有可能在末尾,长度为零个字符。去掉这一行:
i=0(它没有做任何有用的事情)并在其位置放置:

if len(line) < 12:
    continue
如果长度(线)<12:
持续

这将保证数据符合代码的预期。

代码不完整。什么是原子数?您还可以在您的帖子中编辑完整的错误回溯吗?在您的if之前添加if len(line)>11:。顺便说一句,我是什么?公平点。我已将问题编辑为正确。如何改进您的代码?让它工作,然后把它贴上