【问题标题】:In python, how to replace text in every row by looking up in dictionary?在python中,如何通过在字典中查找来替换每一行中的文本?
【发布时间】:2017-03-08 02:14:54
【问题描述】:

如果我有这样的数据集

    id details  
    1  I have an account  
    2  acnt is now closed
    3  he knws my acc no

还有字典

    d ={'acc' : 'account', 'acnt' : 'account', 'knws':'knows'}

如果每一行都是单词列表/字符串,如何替换所有单词?此外,数据集有 50 万行。

输出是这样的

    id details  
    1  I have an account  
    2  account is now closed
    3  he knows my account no

【问题讨论】:

    标签: python string pandas nlp text-mining


    【解决方案1】:

    我认为这是一项蛮力的工作。首先,您必须读取文件的行并将更改后的文本写入新文件。

    对于每一行文本,遍历字典的所有键,进行所需的替换。那部分看起来像这样:

    for line in input_file:
        for word in abbrev_dict:
            if word in line:
                line = line.replace(word, abbrev_dict[word])
        # write the altered line to the output file
    

    这是否会让您朝着解决方案迈进?

    【讨论】:

      【解决方案2】:

      快速而肮脏的方法

         with open('bigfile') as f:
               for line in f: # iterate over each line and replace words with alias
                     print " ".join([d.get(w,w) for w in line.split(" ")] # your desired output
      

      【讨论】:

        猜你喜欢
        • 2017-04-29
        • 1970-01-01
        • 2022-08-17
        • 2017-02-23
        • 1970-01-01
        • 1970-01-01
        • 2017-06-28
        • 2019-07-30
        • 2020-05-25
        相关资源
        最近更新 更多