csv的内容如下:
"Washington-Arlington-Al, DC-VA-MD-WV (MSAD)" 47894 1976
"Grand-Forks, ND-MN" 24220 2006
"Abilene, TX" 10180 1977
通过csv读取所需的输出,找到“”之间的内容 在第1列中,仅获取DC-VA-MD-WV,ND-MN,TX和 将此内容放在新列中。 (用于标准化)
到目前为止,在python中尝试了很多正则表达式模式,但是无法获得正确的模式。
sample=""" "Washington-Arlington-Al, DC-VA-MD-WV (MSAD)",47894,1976
"Grand-Forks, ND-MN",24220,2006
"Abilene, TX",10180,1977 """
open('sample.csv','w').write(sample)
with open('sample.csv') as sample, open('output.csv','w') as output:
reader = csv.reader(sample)
writer = csv.writer(output)
for comsplit in row[0].split(','):
writer.writerow([ comsplit, row[1]])
print open('output.csv').read()
预期输出为:
DC-VA-MD-WV
ND-MN
TX
在新行中
答案 0 :(得分:1)
我会这样做:
with open('csv_file.csv', 'r') as f_in, open('output.csv', 'w') as f_out:
csv_reader = csv.reader(f_in, quotechar='"', delimiter=',',
quoting=csv.QUOTE_ALL, skipinitialspace=True)
csv_writer = csv.writer(f_out)
new_csv_list = []
for row in csv_reader:
first_entry = row[0].strip('"')
relevant_info= first_entry.split(',')[1].split(' ')[0]
row += [relevant_info]
new_csv_list += [row]
for row in new_csv_list:
csv_writer.writerow(row)
如果您有任何问题,请与我们联系。
答案 1 :(得分:1)
这里没有必要使用正则表达式:
(MSAD)
此代码根据示例输入提供您的预期输出:
with open('sample.csv', 'r') as infile, open('expected_output.csv', 'wb') as outfile:
reader = csv.reader(infile)
expected_output = []
for row in reader:
split_by_comma = row[0].split(',')[1]
split_by_space = split_by_comma.split(' ')[1]
print split_by_space
expected_output.append([split_by_space])
writer = csv.writer(outfile)
writer.writerows(expected_output)
答案 2 :(得分:1)
我相信你可以使用这个正则表达式模式,它会在逗号和括号之间提取任何字母数字表达式(带连字符或不带连字符):
import re
BETWEEN_COMMA_PAR = re.compile(ur',\s+([\w-]+)\s+\(')
test_str = 'Washington-Arlington-Al, DC-VA-MD-WV (MSAD)'
result = BETWEEN_COMMA_PAR.search(test_str)
if result != None:
print result.group(1)
这将打印结果:DC-VA-MD-WV
,正如所料。
答案 3 :(得分:0)
您似乎在找到用于查找预期值的regex
权限时遇到了麻烦。
我创建了一个小样本pythext,它将满足您的要求。
基本上,当您检查第一列的每个值的内容时,您可以使用像/(TX|ND-MN|DC-VA-MD-WV)/
我希望这很有用!如果您需要进一步解释,请告诉我。