【问题标题】:File search function does not return location?文件搜索功能不返回位置?
【发布时间】:2017-04-12 13:20:56
【问题描述】:

我正在测试给定文件的输入/输出。每个文件都包含字符串,我将在该文件中搜索“s”并返回该文件中 s 位置的有序列表。该函数没有给出位置,而是给出了整行。为什么?

这是我的功能:

def locate(filename,s):
    lookfor=s
    new_list=[]
    with open(filename) as my_file:
        for num, line in enumerate(my_file):
            if lookfor in line:
                new_list.append(num)
        new_list.sort()
        return new_list

【问题讨论】:

  • sort() 就地工作。所以写两条语句:new_list.sort()return new_list
  • 你好append(..)line。所以很明显它增加了整行。
  • 是的,使用append(line.index(s))
  • @KelseyGreenwood:但是你说的locations是什么意思?列号还是行号?
  • 在这种情况下,for 应该看起来像 for num,line in enumerate(my_file): 而你是 append(num),所以不再有索引了。

标签: python-3.x file loops filereader


【解决方案1】:
def locate(filename,s):
    lookfor=s
    new_list=[]
    with open(filename) as my_file:
        for num, line in enumerate(my_file,1):
            if lookfor in line:
                new_list.append(num)
        new_list.sort()
        return new_list

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    相关资源
    最近更新 更多