这是有史以来第一个问题。我已经尝试了大约一周的时间来寻找解决方案,但最终我不得不问了。我对这个问题的标题也持开放态度。
我正在使用python3
我有一个csv文件(legend.csv),其中包含两个头(键),一个用于数字,一个用于缩写。
每个缩写都有一个对应的数字,这在csv文件中表示。
我还有一个名字列表(list.txt),名字的第一部分通常是某种缩写。
该程序背后的想法是:我想分析csv文件,并在list.txt的名称中添加与缩写相对应的数字。如果可能的话,输出应该是一个新的文本文件。
example of list.txt:
addg-stuff
cbdd-stuff
abc-stuff
add-stuff
example of legend.csv:
number,abbr
0001,addg
0002,cbdd
0003,abc
0004,add
example of desired output:
0003-abc-stuff
0001-addg-stuff
0004-add-stuff
0002-cbdd-stuff
下面的代码找到了缩写,但我不知道如何将相应的数字添加到名称中。Easiest way to cross-reference a CSV file with a text file for common strings
上面的链接是我发现如何提取匹配字符串的地方,但不确定从哪里开始。
import csv
with open("legend.csv") as csvfile:
reader = csv.reader(csvfile)
searchstring = {row[1] for row in reader}
num = {row[0] for row in reader}
with open("list.txt") as txtfile:
for names in txtfile:
for i in searchstrings:
if i in name:
matching = (name) #not sure where to go from here. If matching is printed, the names are found that contain the abbr.
这绝对是个新手,我刚开始使用python一个月左右。任何帮助都是非常感谢的,特别是如果你有任何好的资源来处理这种情况或一般的python。
发布于 2017-07-05 18:55:18
您可以尝试这样做:
import csv
f1 = open('legend.csv')
f1 = csv.reader(f1) #splitting at instances of commas
f1 = list(f1)
f2 = open('list.txt').read().splitlines() #reading every line in the txt file
for i in f2:
for b in f1[1:]:
if i.split("-")[0] == b[1]:
print str(b[0])+"-"+i
输出:
0001-addg-stuff
0002-cbdd-stuff
0003-abc-stuff
0004-add-stuff
在双for循环中,算法从txt文件中取出一行,然后从csv文件中取出一行。请注意,f1[1:]
是列表切片。这意味着我们从csv文件中的头文件开始,这对我们解决问题没有帮助。从那里,算法尝试确定缩写是否包含在该行的第一部分中,在本例中存储为i
。如果是,则以所需输出的样式打印数字和行。
https://stackoverflow.com/questions/44913522
复制相似问题