gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:17 25 4
gpt4 key购买 nike

我有一个.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()

最佳

关于Python从文本文件中拆分并查找特定字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55060359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com