簡體   English   中英

Python - 用另一個列表替換字符列表

[英]Python - Replace list of characters with another list

我有兩個清單:

wrong_chars = [
    ['أ','إ','ٱ','ٲ','ٳ','ٵ'],
    ['ٮ','ݕ','ݖ','ﭒ','ﭓ','ﭔ'],
    ['ڀ','ݐ','ݔ','ﭖ','ﭗ','ﭘ'],
    ['ٹ','ٺ','ٻ','ټ','ݓ','ﭞ'],
]

true_chars = [
    ['ا'],
    ['ب'],
    ['پ'],
    ['ت'],
]

對於給定的字符串,我想將wrong_chars的條目替換為wrong_chars中的true_chars 在python中有沒有一種干凈的方法來做到這一點?

string模塊來救援!

有一個非常方便的函數作為string模塊的一部分,稱為translate ,它完全符合您的要求,盡管您必須將翻譯映射作為字典傳遞。

文檔在 這里

下面顯示了一個基於tutorialapoint教程的示例:

>>> from string import maketrans

>>> trantab = maketrans("aeiou", "12345")
>>> "this is string example....wow!!!".translate(trantab)

th3s 3s str3ng 2x1mpl2....w4w!!!

看起來您在這里使用的是 unicode,但工作方式略有不同。 你可以看看這個問題來了解一下,但這里有一個更適合你的例子:

translation_dict = {}
for i, char_list in enumerate(wrong_chars):
    for char in char_list:
        translation_dict[ord(char)] = true_chars[i]

example.translate(translation_dict)

我將您的兩個錯誤和真實字符合並到了錯誤字典列表中,以及應該用它們替換的內容。 所以你在這里:
鏈接到工作示例http://ideone.com/mz7E0R
和代碼本身

given_string = "ayznobcyn"
correction_list = [
                    {"wrongs":['x','y','z'],"true":'x'},
                    {"wrongs":['m','n','o'],"true":'m'},
                    {"wrongs":['q','r','s','t'],"true":'q'}
                  ]

processed_string = ""
true_char = ""

for s in given_string:
    for correction in correction_list:
        true_char=s
        if s in correction['wrongs']:
            true_char=correction['true']
            break
    processed_string+=true_char

print given_string
print processed_string

這段代碼可以更優化,當然我不關心 unicode 問題(如果有的話),因為我看到你在使用波斯語。 你應該注意這一點。

#!/usr/bin/env python
from __future__ import unicode_literals

wrong_chars = [
    ['1', '2', '3'],
    ['4', '5', '6'],
    ['7'],
]
true_chars = 'abc'

table = {}
for keys, value in zip(wrong_chars, true_chars):
    table.update(dict.fromkeys(map(ord, keys), value))
print("123456789".translate(table))

輸出

aaabbbc89

在我的想法中,您可以只制作一個包含真實字符的列表,如下所示:

NewChars = {["ا"،"أ"،"إ"،"آ"], ["ب"،"بِ"،"بِ"،]} 
# add all true characters to the first of lists and add all lists to a dict, then:
Ch="إ"
For L in NewChars:
    If Ch in L: return L[0]

暫無
暫無

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

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