搜索字符串并找出字符串所在的行数[PYTHON]

2024-10-02 02:42:03 发布

您现在位置: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.read()
for i in list:
    if content.find(i):
        print (i, "in", content.count('\n') + 1)

如有任何意见或建议,我们将不胜感激。你知道吗

彼得


Tags: 字符串代码in定位txtexamplecontentconnection
1条回答
网友
1楼 · 发布于 2024-10-02 02:42:03
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()

相关问题 更多 >

    热门问题