【问题标题】:Process each line of text file using Python使用 Python 处理文本文件的每一行
【发布时间】:2016-09-16 07:51:43
【问题描述】:

我对 Python 还很陌生。我有一个文本文件,其中包含许多以下格式的数据块以及其他不必要的块。

    NOT REQUIRED :: 123
    Connected Part-1:: A ~$
    Connected Part-3:: B ~$         
    Connector Location:: 100 200 300 ~$
    NOT REQUIRED :: 456
    Connected Part-2:: C ~$

我希望提取与每个属性(连接的第 1 部分,连接器位置)对应的信息(A、B、C、100 200 300)并将其存储为列表以供以后使用。我准备了以下代码,它读取文件、清理行并将其存储为列表。

    import fileinput
    with open('C:/Users/file.txt') as f:
    content = f.readlines()
    for line in content:
            if 'Connected Part-1' in line or 'Connected Part-3' in line:
                    if 'Connected Part-1' in line:
                            connected_part_1 = [s.strip(' \n ~ $ Connected Part -1 ::') for s in content]                               
                            print ('PART_1:',connected_part_1)                                  
                    if 'Connected Part-3' in line:
                            connected_part_3 = [s.strip(' \n ~ $ Connected Part -3 ::') for s in content]                               
                            print ('PART_3:',connected_part_3)                              
            if 'Connector Location' in line:                        
                    # removing unwanted characters and converting into the list
                    content_clean_1 = [s.strip('\n ~ $ Connector Location::') for s in content] 
                    #converting a single string item in list to a string
                    s = " ".join(content_clean_1)
                    # splitting the string and converting into a list
                    weld_location= s.split(" ")
                    print ('POSITION',weld_location)    

这是输出

   PART_1: ['A', '\t\tConnector Location:: 100.00 200.00 300.00', '\t\tConnected Part-3:: C~\t']
   POSITION ['d', 'Part-1::', 'A', '\t\tConnector', 'Location::', '100.00', '200.00', '300.00', '\t\tConnected', 'Part-3::', 'C~\t']
   PART_3: ['1:: A', '\t\tConnector Location:: 100.00 200.00 300.00', '\t\tConnected Part-3:: C~\t']

从这个程序的输出中,我可以得出结论,因为“内容”是由文件中所有字符组成的字符串,所以程序没有读取单独的行。相反,它将所有文本视为单个字符串。在这种情况下有人可以帮忙吗?

我期待以下输出:

   PART_1: ['A']
   PART_3: ['C']
   POSITION: ['100.00', '200.00','300.00']

(注意)当我使用包含单行数据的单个文件时,它工作正常。抱歉问了这么长的问题

【问题讨论】:

  • 你为什么要检查 if 'Connected Part-1' in line or 'Connected Part-3' in line: 然后再检查嵌套的 if ?为什么不只是 if 'Connected Part-1' in line: 然后 elif Connected Part-3' in line: 和 if/or if?

标签: python python-3.x


【解决方案1】:

我会尽量说清楚,并说明没有regex 的情况下我会怎么做。首先,所呈现代码的最大问题是,当使用string.strip 函数时,会读取整个内容列表:

connected_part_1 = [s.strip(' \n ~ $ Connected Part -1 ::') for s in content]

内容是整个文件行,我想你想要的只是:

connected_part_1 = [line.strip(' \n ~ $ Connected Part -1 ::')]

如何解析文件有点主观,但考虑到作为输入发布的文件格式,我会这样做:

templatestr = "{}: {}"

with open('inputreadlines.txt') as f:
    content = f.readlines()
    for line in content:
        label, value = line.split('::')
        ltokens = label.split()
        if ltokens[0] == 'Connected':
            print(templatestr.format(
                ltokens[-1], #The last word on the label
                value.split()[:-1])) #the split value without the last word '~$'
        elif ltokens[0] == 'Connector':
            print(value.split()[:-1]) #the split value without the last word '~$'
        else: #NOT REQUIRED
            pass

您可以使用string.strip 函数来删除有趣的字符“~$”,而不是像示例中那样删除最后一个标记。

【讨论】:

  • :感谢您的输入,但是,从文本文件中比较关键字(连接的第 1 部分,连接器位置)的“If”条件不满足。程序正在执行“else”。显然我在上面的代码中使用了文本文件中提到的确切关键字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 2018-03-22
  • 1970-01-01
  • 2016-09-02
  • 1970-01-01
相关资源
最近更新 更多