【问题标题】:dissociate firstname/surname by comparing通过比较分离名字/姓氏
【发布时间】:2014-08-14 22:35:02
【问题描述】:

我有一个包含 2000 行的 CSV 数据集,其中包含一个关于名字/姓氏的凌乱列。在本专栏中,我需要区分名字和姓氏。为此,我有一个基地,其中包含过去 20 年在法国给出的所有姓氏。

所以,源数据库看起来像:

"name"; "town"
"Johnny Aaaaaa"; "Bordeaux"
"Bbbb Tom";"Paris"
"Ccccc Pierre Dddd" ; "Lyon"
...

我想获得类似的东西:

"surname"; "firstname"; "town"
"Aaaaaa"; "Johnny "; "Bordeaux"
"Bbbb"; "Tom"; "Paris"
"Ccccc Dddd" ; "Pierre"; "Lyon"
...

还有,我的名字参考数据库:

"firstname"; "sex"
"Andre"; "M"
"Bob"; "M"
"Johnny"; "M"
...

从技术上讲,我必须将第一个碱基的每一行与第二个碱基的每个字段进行比较,以确定哪个字符链对应于第一个名称... 我不知道该怎么做。

欢迎任何想法...谢谢。

【问题讨论】:

  • 你的问题不是很清楚。您可以使用 str.split() 分隔第一列中的名字和姓氏,但我不明白您要进行的比较。
  • 嗯,好的。我明白了,对不起。关键是我不能简单地将名字和姓氏分开,因为在每一行中的数据都不相似。例如:在第一行中,我有名字/姓氏,但在第二行中,我有姓氏/名字,或者在第三行中只有名字的第一个字母,或者只有先生-夫人/姓氏......这是一个正确的混乱!所以我想比较是自动获得什么是名字和什么不是名字的唯一方法。最后,我们得到两列:一列有名字,一列有其余的。我错了?

标签: python database csv


【解决方案1】:

看起来你想要

  1. 从 input.csv 文件中读取数据
  2. 提取名称并将其拆分为名字和姓氏
  3. 使用名字获取性别
  4. 可能会再次将数据写入新的 csv 或打印。

您可以按照以下方法进行操作。您可以使用正则表达式进行更复杂的拆分,但这里是使用条命令的基本内容:

inFile=open('input.csv','r')
rows=inFile.readlines()
newData=[]
if len(rows) > 1:
    for row in rows[1:]:
         #Remove the new line chars at the end of line and split on ;
         data=row.rstrip('\n').split(';')

         #Remove additional spaces in your data
         name=data[0].strip()

         #Get rid of quotes
         name=name.strip('"').split(' ')
         fname=name[1]
         lname=name[0]
         city=data[1].strip()
         city=city.strip('"')

         #Now you can get the sex info from your other database save this in a list to get the sex info later
         sex='M' #replace this with your db calls
         newData.append([fname, lname, sex, city])

inFile.close()
#You can put all of this in the new csv file by something like this (it seperates the fileds using comma):

outFile=open('otput.csv','w')
for row in newData:
    outFile.write(','.join(row))
    outFile.write('\n')
outFile.close(

【讨论】:

  • 谢谢。一切都很好,除了我拆分名字和姓氏的步骤。我的主要问题是将它们分开,目前仅在一个字段中随机混合...再次感谢所有这些行,它们将很有用...之后! :)
【解决方案2】:

嗯。最后,我选择了“蛮力”方法:每行的每个术语都与我的第二个基地的 11.000 个键进行比较(在字典中转换)。不聪明,但高效。

for row in input:       
    splitted = row[0].lower().split()       
    for s in splitted :         
        for cle, valeur in dict.items() :       
            if cle == s :                   
                print ("{} >> {}".format(cle, valeur))  

仍然欢迎所有关于更漂亮解决方案的想法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-22
    • 2015-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    相关资源
    最近更新 更多