[英]Convert tab delimited txt file into csv file comma separated
我有這個文本文件,我想把它轉換成逗號分隔的文件
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)
請問有什么幫助嗎?
鑒於這些行,您似乎可以使用正則表達式來獲取五個字段。 類似於以下內容:
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.