使用字典替换字母

时间:2018-11-12 01:53:34

标签: python

我有一段文字,我通过字素将其分为不同的声音。这些字素现在是列表的一部分,如下所示:

graphemes = ["th", "e", "g", "i", "r", "l", "th", "a", "t", "r", "ea", "d", "s", ...]

除此之外,我还有一本字典,将其中一些字素与数字链接:

graph_nums = {"th":1, "s":2, "t":3, ...}

最后,我有一组条件。例如,“如果-s在元音之后”或“如果-t在辅音之前”。

我想做的是在字素列表上进行迭代,如果满足条件之一,则用相应的编号替换字素。

这是我到目前为止尝试做的事情:

special_graphemes = ["s", "t"...] #a list with the characters that are mentioned in the conditions
vowels = ["a", "e", "i", "o", "u", ...] #a list with all the vowels and dipthongs 
consonants = ["b", "c", "d", ...] #a list of all consonants and groups of consonants
output = ""

for grapheme in graphemes: #iterate over each grapheme
    if grapheme in special_graphemes: #if the grapheme is one of the graphemes that needs to be replaced by a number
        if graphemes[grapheme-1] in vowels: #for a condition like "if -s comes after a vowel", it needs to be checked whether the previous grapheme is a vowel
            output += graph_nums.get(num) #if the previous condition applies, then replace the grapheme by its number, according to the dictionary
       elif XXXX #other conditions checked in a similar way
    else:
        output += grapheme #otherwise, just keep the grapheme as it is
print(output)

但是,当我运行此命令时,出现有关索引的错误(即,这是错误的:graphemes[grapheme-1])。然后,我该如何访问我感兴趣的职位并在必要时更换他们?

此外,我也不确定我访问字典和替换字素的方式是否正确。

1 个答案:

答案 0 :(得分:0)

使用Python列表理解

尝试一下:

private void button1_Click(object sender, EventArgs e)
{
    dataGridView1.Rows['row_index'].Selected = true;
}

输出

[1,'e','g','i','r','l',1,'a',3,'r','ea','d',2]

相关问题