簡體   English   中英

Python-使用.txt文件和編解碼器進行replace()和utf-8編碼/解碼

[英]Python - replace() and utf-8 encoding / decoding using .txt files with codecs

我在處理整個UTF-8解碼/編碼時遇到了一些麻煩。 以下功能應替換給定數據中的多個單詞。 其背后的背景是,我正在解析多個PDF文檔並嘗試查找某些關鍵字以備將來使用。 但是由於將PDF解析為字符串會導致拼寫錯誤,因此此功能可以解決該問題。 我大幅縮減了功能,通常會有更多的替換品和更多的類型,依此類推,盡管主要問題仍然存在於這一小部分。

盡管replaceSimilar1()可以很好地工作,但是replaceSimilar2()不會以我想要的方式替換單詞。 txt文檔包含與數組完全相同的條目,並保存在UTF-8中。 我知道,這與某些部分的編碼/解碼有關,但是無論我到目前為止嘗試了什么,都無濟於事。 沒有引發異常,只是沒有替換給定的單詞。

這是我的代碼(包括測試主代碼):

# -*- coding: utf-8 -*-
import codecs


RESOURCE_PATH="resource"


def replaceSimilar1(data, type):

    ZMP_array=["zählpunkt:", "lpunkt:", "zmp:", "hipunkt:", "h punkt:", "htpunkt:", ]
    adress_array=["zirkusweg", "zirktisweg", "rkusweg", "zirnusweg", "jürgen-töpfer", "-töpfer", "jürgen-", "pfer-stras", "jürgentöpfer", "ürgenlöpfer"]

    if type=="adress":
        array=adress_array

    elif type=="zmp":
        array=ZMP_array

    else:
        array=["",""]

    for word in array:
        data=data.lower().replace(word, type)

    return data


def replaceSimilar2(data, type):
    c_file=codecs.open(RESOURCE_PATH+"\\"+type+".txt", "r+", "utf-8")
    for line in c_file.readlines():
        data=data.lower().replace(line.encode("utf-8"), type)
    c_file.close()
    return data


if __name__=="__main__":

    testString="this lpunkt: should be replaced by zmp as well as -töpfer should be replaced by adress..."
    print("testString: "+testString)

    #PART 1:
    replaced1=replaceSimilar1(testString, "zmp")
    replaced1=replaceSimilar1(replaced1, "adress")
    print("replaced 1: "+replaced1)

    # PART 2:
    replaced2=replaceSimilar2(testString, "zmp")
    replaced2=replaceSimilar2(replaced2, "adress")
    print("replaced 2: "+replaced2)

問題不在於編碼,而是事實,當您讀取文件時, line以換行符char( \\n )結尾。 使用line.strip()代替,將函數更改為

def replaceSimilar2(data, type):
    c_file=codecs.open(RESOURCE_PATH+"\\"+type+".txt", "r+", "utf-8")
    for line in c_file:
        data=data.lower().replace(line.strip().encode("utf-8"), type)
    c_file.close()
    return data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM