【问题标题】:Search for a character in a line and append entire line to a list在一行中搜索一个字符并将整行附加到列表中
【发布时间】:2017-10-01 18:56:11
【问题描述】:

尝试通过查找文档 ID 创建字典文件和发布列表文件。它应该打开文件并搜索术语“.I”并将该行作为列表元素

#Function which find the doc ID

#There is a list I created with name idList

def idTag():

file = open('cacm.txt', 'r')

line = file.readline()

while line:

if '.I' in line:

 idList.append(line)

elif not '.I' in line:

 line = file.readline()

elif not line:

 file.close()`

【问题讨论】:

  • 您有问题吗? (什么不起作用?)
  • 请缩进你的代码!
  • 如果我的回答解决了您的问题,您可以点击旁边的勾号将其标记为已接受。

标签: python


【解决方案1】:

我不太明白您要做什么,但是如果我正确阅读了问题,您希望遍历文件的行,过滤包含字符串 '.I' 的行。因此,这应该有效:

def idTag():
    # Create the list to collect the results in
    idList = []
    # Better way of opening a file;
    # closes it automatically when the `with` statement is finished
    with open('cacm.txt', 'r') as file:
        # Read each line from the file
        for line in file:
            # Filter those that have `.I` in them
            if '.I' in line:
                idList.append(line)
    return line

这利用了文件可以循环读取的事实,一次读取一行。

【讨论】:

  • [line for line in file if '.I' in line] 可能是最 Pythonic 的方式
猜你喜欢
  • 1970-01-01
  • 2018-05-24
  • 2013-06-09
  • 2013-07-15
  • 1970-01-01
  • 2013-11-24
  • 2016-11-13
  • 1970-01-01
  • 2015-03-29
相关资源
最近更新 更多