[英]Apply a function to each line of a CSV file in python
我有一個正則表達式,我想將其應用於CSV文件的每一行。
這是基本上刪除一個數字前的所有逗號的函數。 該函數對於字符串來說工作得很好 。
Input : text = "52A, XYZ Street, ABC District, 2, M, Brown
Function : re.sub('(?<!\s[\dA-Z]),(?!\s+\d,?)', '', text)
Output : '52A XYZ Street ABC District, 2, M, Brown'
但是,我有一個包含數百行這樣的CSV文件。 例如
1, 5273249, 1061/72, 150-CF, S/O:XVZ, 1, ABX, 45, 0, Husband, 9213
1, 5272849, 1063/36, 150-AS, S/O:XVZ, 1, ABX, 45, 0, Wife, 9253
1, 5274549, 10626/12, 150-RT, S/O:XVZ, 1, ABX, 45, 0, Son, 9214
我嘗試使用CSV閱讀器讀取它並應用該功能,但不幸的是,它沒有產生任何輸出。 我在這里做錯了什么:
def myFunction(text):
return re.sub('(?<!\s[\dA-Z]),(?!\s+\d,?)', '', text)
import csv
with open('temp1.csv', 'r') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
for row in spamreader:
l = ','.join(row)
myFunction(l)
有一個方便的模塊,稱為fileinput
,可讓您輕松地逐行編輯文件。
看一眼:
import re
import fileinput
# For each line
for line in fileinput.input(files='example.csv', inplace=True, backup='.bak'):
# Replace it with the regex you provided
print(re.sub('(?<!\s[\dA-Z]),(?!\s+\d,?)', '', line), end='')
輸出:
Before:
1, 5273249, 1061/72, 150-CF, S/O:XVZ, 1, ABX, 45, 0, Husband, 9213
1, 5272849, 1063/36, 150-AS, S/O:XVZ, 1, ABX, 45, 0, Wife, 9253
1, 5274549, 10626/12, 150-RT, S/O:XVZ, 1, ABX, 45, 0, Son, 9214
After:
1, 5273249, 1061/72, 150-CF S/O:XVZ, 1, ABX, 45, 0, Husband, 9213
1, 5272849, 1063/36, 150-AS S/O:XVZ, 1, ABX, 45, 0, Wife, 9253
1, 5274549, 10626/12, 150-RT S/O:XVZ, 1, ABX, 45, 0, Son, 9214
如果需要,這還會為您創建一個方便的example.csv.bak
文件!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.