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

时间:2019-03-08 09:35:18

标签: python

我有一个.csv file格式的原始数据,并想将其转换为(L2-CR666 Reception Counter) L2-CR666 Reception Counter has been forced. (L7-CR126 Handicapped Toilet) L7-CR126 Handicapped Toilet has been forced. 格式。

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

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()

我尝试了以下代码,但无法达到规定的结果。我在哪里弄错了?

// create table to hold users/clickers info
create table user(id int primary key auto_increment,username varchar(30));

// lets insert into user table
insert into user(id,username) values(101,'Nancy');

//create table ad_tracking
    create table Ad_Tracking(id int(11) primary key auto_increment,likes int(11), views int(11),video_clicks int(11) ad_info text);

// Create ad_like table
create table Ad_like(id int(11) primary key auto_increment,likes int(11), ad_id int(11),user_id int(11));

// Create ad_viewers table
create table Ad_view(id int(11) primary key auto_increment,views int(11), ad_id int(11),user_id int(11));



// Create video_click table
create table Ad_video_click(id int(11) primary key auto_increment,video_click int(11), ad_id int(11),user_id int(11));

4 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

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()

最佳

答案 1 :(得分:2)

您可以使用.partition()截断)之前的所有内容,然后只需相应地替换不需要的部分。另外,使用with语句时不必关闭文件,因为它会自动为您关闭文件,也不必导入csv库来保存扩展名为.csv的文件。

以下代码输出您想要的结果:

infile_path = "Converted Detection\\Testing 01\\2019-02-21.txt"
outfile_path = "Converted Detection\\Converted CSV\\log.csv"

with open(infile_path, "r") as infile, open(outfile_path, "+w") as outfile:
    for line in infile:
        line = line.partition(")")[2].replace(" has been forced.", ", forced").strip()
        outfile.write(line + "\n")

答案 2 :(得分:1)

第一个for循环正在读取infile。无需重新读取infile和第二个循环。 此外,with块将负责关闭文件。

for line in infile:
    line = line.replace("(", "")
    outfile.write(', '.join(line.split(')')))

答案 3 :(得分:0)

我建议使用:

lineout = ', '.join(linein.replace('(','').replace(')','').split(' has been ')

其中:

linein = line.strip()