将制表符分隔的txt文件转换为以逗号分隔的csv文件

时间:2019-03-03 17:17:01

标签: python string csv tabs comma

我有这个文本文件,我想将其转换为逗号分隔的文件

antecedents    consequents    support    confidence    lift
-------------  -------------  ---------  ------------  ------
  398  frozenset(['LM = 25', 'DIAB = n', 'SMOK = y'])     frozenset(['AL = 1'])       0.25             1  1.33333
  461  frozenset(['Age = 80', 'LM = 15', 'CHOL = 200'])   frozenset(['AL = 1'])       0.25             1  1.33333
  837  frozenset(['RCA = 80', 'Age = 80', 'SMOK = y'])    frozenset(['AL = 1'])       0.25             1  1.33333

我应用了pandas和csv,但是它没有分隔列,它仅分隔像这样的原始文件

antecedents    consequents    support    confidence    lift
-------------  -------------  ---------  ------------  ------
"  398  frozenset(['LM = 25', 'DIAB = n', 'SMOK = y'])     frozenset(['AL = 1'])       0.25             1  1.33333"
"  461  frozenset(['Age = 80', 'LM = 15', 'CHOL = 200'])   frozenset(['AL = 1'])       0.25             1  1.33333"
"  837  frozenset(['RCA = 80', 'Age = 80', 'SMOK = y'])    frozenset(['AL = 1'])       0.25             1  1.33333"

这是我使用的代码 1-

dataframe = pd.read_csv("/Users/user/PycharmProjects/Apriori /Rules.txt",delimiter="\t")
dataframe.to_csv("newDoc.csv", encoding='utf-8', index=False)

2-

txt_file = r"/Users/user/PycharmProjects/Apriori /Rules.txt"
csv_file = r"mycsv.csv"

in_txt = csv.reader(open(txt_file, "rb"), delimiter = '\t')
out_csv = csv.writer(open(csv_file, 'wb'))

out_csv.writerows(in_txt)

请帮忙吗?

1 个答案:

答案 0 :(得分:0)

给出这些行,就好像您可以使用正则表达式来抓取这五个字段一样。类似于:

import csv
import re

# looks like a consistent format given the example text:
line_re = re.compile('^\s*(\d+)\s+(frozenset.*?\))\s*(frozenset.*?\))\s*(\S+)\s+(\S+)\s+(\S+)$')
txt = '''antecedents    consequents    support    confidence    lift
-------------  -------------  ---------  ------------  ------
  398  frozenset(['LM = 25', 'DIAB = n', 'SMOK = y'])     frozenset(['AL = 1'])       0.25             1  1.33333
  461  frozenset(['Age = 80', 'LM = 15', 'CHOL = 200'])   frozenset(['AL = 1'])       0.25             1  1.33333
  837  frozenset(['RCA = 80', 'Age = 80', 'SMOK = y'])    frozenset(['AL = 1'])       0.25             1  1.33333'''

with open('mycsv.csv', 'w') as f:
    writer = csv.writer(f)
    for line in txt.splitlines():
        mo = line_re.match(line)
        if mo:
            writer.writerow(mo.groups())


cat mycsv.csv
398,"frozenset(['LM = 25', 'DIAB = n', 'SMOK = y'])",frozenset(['AL = 1']),0.25,1,1.33333
461,"frozenset(['Age = 80', 'LM = 15', 'CHOL = 200'])",frozenset(['AL = 1']),0.25,1,1.33333
837,"frozenset(['RCA = 80', 'Age = 80', 'SMOK = y'])",frozenset(['AL = 1']),0.25,1,1.33333