[英]Convert tab delimited txt file into csv file comma separated
I have this text file and I want to convert it into comma separated file我有这个文本文件,我想把它转换成逗号分隔的文件
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
I applied pandas and csv but it doesn't separate columns, it only separates raws like this我应用了 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"
This is the code I used 1-这是我使用的代码 1-
dataframe = pd.read_csv("/Users/user/PycharmProjects/Apriori /Rules.txt",delimiter="\t")
dataframe.to_csv("newDoc.csv", encoding='utf-8', index=False)
2- 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)
Any help please?请问有什么帮助吗?
Given the lines it looks as if you could use a regular expression to grab the five fields.鉴于这些行,您似乎可以使用正则表达式来获取五个字段。 Something along the lines of:
类似于以下内容:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.