簡體   English   中英

python如何讀取tsv文件,清理它並另存為新文件?

[英]python how to read a tsv file, clean it and save as new file?

我想從我的 tsv 文件的第 4 列中刪除所有標點符號,然后保存整個文件。 這是我的代碼:

import csv
import string

exclude = set(string.punctuation)

with open("test1") as tsvfile:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    for line in tsvreader:
        line[4] = ''.join(ch for ch in line[4] if ch not in exclude)
    tsvfile.close()

上面的代碼工作正常,但我的文件沒有保存我所做的更改。 如何保存舊文件中的更改?

您沒有寫任何更改,您只是更改每行中的每個第五個元素並且不對其執行任何操作,如果您想更改原始文件,您可以寫入tempfile並執行shutil.move以將原始文件替換為更新溫度:

import string

exclude = string.punctuation
from tempfile import NamedTemporaryFile
from shutil import move

with open("test1") as tsvfile, NamedTemporaryFile(dir=".",delete=False) as t:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    temp = csv.writer(t,delimiter="\t")
    for row in tsvreader:
        row[4] = row[4].strip(exclude)
        temp.writerow(row)

move(t.name,"test1")

如果你想創建一個新文件而不是更新原始文件,你只需要打開一個新文件並寫入每個清理過的行:

with open("test1") as tsvfile, open("out","w") as  t:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    temp = csv.writer(t,delimiter="\t")
    for row in tsvreader:
        row[4] = row[4].strip(exclude)
        temp.writerow(row)

str.strip(exclude)標點符號str.strip(exclude)就足夠了。 如果你想從任何地方刪除你可以回到''.join([ch for ch in line[4] if ch not in exclude])但是如果你從任何地方刪除那么你應該使用str.translate

 row[4] = row[4].translate(None,exclude) 

如果要添加空格:

from string import maketrans
tbl = maketrans(exclude," "*len(exclude))

....
row[4] = row[4].translate(tbl) 

最后,如果您實際上是指第四列,那么它將是row[3]而不是row[4]

你說你想要一個新文件,所以你需要打開第二個文件並將清理過的行寫入其中:

import csv
import string

exclude = string.punctuation

with open("test1") as tsvfile, open('out.csv') as outfile:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    tsvwriter = csv.writer(outfile, delimiter="\t")
    for row in tsvreader:
        row[4] = row[4].translate(None, string.punctuation)
        tsvwriter.writerow(row)

這使用str.translate()從列中刪除所有不需要的標點符號。 以上適用於 Python 2。對於 Python 3,請使用:

row[4] = row[4].translate({ord(c): None for c in string.punctuation})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM