Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.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,如何搜索字符串并找到字符串所在的行号 比如说 >>> findlinenb('example.txt', ['desktop', 'connection', 'processor']) desktop in 23 connection in 35, 38, 35 processor in 4, 5, 6, 8 我的代码: def findlinenb (filename, list): file = open(filename, "r") content = file.rea

如何搜索字符串并找到字符串所在的行号

比如说

>>> findlinenb('example.txt', ['desktop', 'connection', 'processor'])
desktop in 23
connection in 35, 38, 35
processor in 4, 5, 6, 8
我的代码:

def findlinenb (filename, list):
file = open(filename, "r")
content = file.read()
for i in list:
    if content.find(i):
        print (i, "in", content.count('\n') + 1)
非常感谢您的任何想法或建议


Peter

Simply
grep-n“your_string”your_file.txt
感谢您的快速回复。
words = ['desktop', 'connection', 'processor']
occurrences = dict((w, []) for w in words)
with open("example.txt") as f:
    for i, line in enumerate(f, 1):
        for w in words:
            if w in line:
                occurrences[w].append(i)
print occurrences.items()