Skip to main content
 首页 » 编程设计

Python从文本文件中拆分并查找特定字符串

2025年05月04日35zhujiabin

我有一个.txt 文件 格式的原始数据,我想将其转换为.csv 文件 格式。

这是来自 txt 文件的示例数据:

(L2-CR666 Reception Counter) L2-CR666 Reception Counter has been forced. 
(L7-CR126 Handicapped Toilet) L7-CR126 Handicapped Toilet has been forced. 

我想达到以下结果:

L2-CR666 Reception Counter, forced 
L7-CR126 Handicapped Toilet, forced 

我尝试了以下代码,但未能达到规定的结果。我哪里做错了?

import csv 
 
with open('Converted Detection\\Testing 01\\2019-02-21.txt') as infile, open('Converted Detection\\Converted CSV\\log.csv', 'w') as outfile: 
    for line in infile: 
        outfile.write(infile.read().replace("(", "")) 
        for line in infile: 
            outfile.write(', '.join(infile.read().split(')'))) 
            outfile.close() 

请您参考如下方法:

你可以试试这个:

with open('Converted Detection\\Testing 01\\2019-02-21.txt') as infile, open('Converted Detection\\Converted CSV\\log.csv', 'w') as outfile: 
    for line in infile: 
        # Get text inside () 
        text = line[line.find("(")+1:line.find(")")] 
        # Remove \r\n         
        line = line.rstrip("\r\n") 
        # Get last word 
        forcedText = line.split(" ")[len(line.split(" "))-1] 
        # Remove . char 
        forcedText = forcedText[:len(forcedText)-1] 
        outfile.write(text+", "+forcedText+"\n") 
 
    outfile.close() 

最佳