在fi中查找字符串

2024-05-19 10:22:35 发布

您现在位置:Python中文网/ 问答频道 /正文

第一次真正使用文件和I/O。我通过测试程序运行我的代码,测试程序通过我的代码调用不同的文件。因此,我在下面将文件表示为“filename”,在该文件中查找的字符串表示为“s”。我很确定我已经看完了代码的每一行并正确地搜索了字符串。这就是我所拥有的:

def locate(filename, s):

    file= open(filename)
    line= file.readlines()
    for s in line:
        if s in line:
            return [line.count]

我知道回路线不对。如何将我要查找的字符串所在的行号作为列表返回?你知道吗


Tags: 文件字符串代码in程序运行forifdef
3条回答

您可以使用^{}。你知道吗

示例文本文件

hello hey s hi
hola
s

代码

def locate(filename, letter_to_find):

    locations = []
    with open(filename, 'r') as f:
        for line_num, line in enumerate(f):
            for word in line.split(' '):
                if letter_to_find in word:
                    locations.append(line_num)
    return locations

输出

[0, 2]

我们可以看到,第0行和第2行的字符串s
注意:计算机从0开始计数

发生什么事了

  1. 打开具有读取权限的文件。

  2. 对每行进行迭代,enumerate在执行时对它们进行遍历,并跟踪line_num中的行号。

  3. 迭代行中的每个单词。

  4. 如果传递给函数的letter_to_findword中,它将line_num附加到locations

  5. 返回locations

这些是问题线

for s in line:
    if s in line:

必须将line读入除s之外的另一个变量

def locate(filename, s):

    file= open(filename)
    line= file.readlines()
    index = 0;
    for l in line:
        print l;
        index = index + 1
        if s in l:
            return index


print locate("/Temp/s.txt","s")

可以使用^{}跟踪行号:

def locate(filename, s):
    with open(filename) as f:
        return [i for i, line in enumerate(f, 1) if s in line]

如果可以从第一行和第三行找到搜索的字符串,它将生成以下输出:

[1, 3]

相关问题 更多 >

    热门问题