簡體   English   中英

如何查找和替換Python中的Unicode字符串?

[英]How To Find and Replace Unicode String in Python?

我有一個包含 Unicode 個字符串列表的文本文件。 比方說list.txt ,我有另一個字典文件dict.txt ,它包含一個單詞列表(也是 Unicode),需要在第一個文件中搜索並替換為其他內容。 但是,我的代碼執行時沒有錯誤,但沒有正確執行查找/替換。

list.txt

राम गोपाल
राम प्रसाद

等等

dict.txt

गोपाल
प्रसाद

find_replace.py

import string

# read the dictionary file of terms (each term in one line)
terms = open('dict.txt', encoding='utf-8').read().splitlines()

# read the file that contains terms to be replaced
original = open('list.txt', encoding='utf-8').read()

# initialize
replaced = ""

for term in terms:
    replaced = original.replace(term, u"")

print(replaced)

關於如何做到這一點的任何建議?

你可以這樣做:

# read the dictionary file of terms (each term in one line)
terms = open('dict.txt', encoding='utf-8').read().splitlines()

# read the file that contains terms to be replaced
original = open('list.txt', encoding='utf-8').read()

# initialize
replaced = original

for term in terms:
    replaced = replaced.replace(term, u'something else')

print(replaced)

暫無
暫無

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

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