首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用字典替换字母

用字典替换字母
EN

Stack Overflow用户
提问于 2018-11-12 01:53:34
回答 1查看 75关注 0票数 0

我有一段文字,我用图形符号把不同的声音分开。这些图形符号现在是列表的一部分,如下所示:

代码语言:javascript
复制
graphemes = ["th", "e", "g", "i", "r", "l", "th", "a", "t", "r", "ea", "d", "s", ...]

除此之外,我还有一本字典,它把一些图形符号和一个数字联系在一起:

代码语言:javascript
复制
graph_nums = {"th":1, "s":2, "t":3, ...}

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

我想要做的是对图形素列表进行迭代,如果满足其中一个条件,然后用相应的数字替换该字素。

到目前为止,我一直试图这样做:

代码语言:javascript
复制
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])。我怎样才能获得我感兴趣的职位,并在必要时更换它们?

另外,我也不确定我访问字典和替换图形符号的方式是否正确。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-12 02:40:33

使用Python的理解

试试这个:

代码语言:javascript
复制
graphemes = ["th", "e", "g", "i", "r", "l", "th", "a", "t", "r", "ea", "d", "s"]
graph_nums = {"th":1, "s":2, "t":3}
out_graphemes = [ x for x in (map(graph_nums.get, graphemes, graphemes)) ]
print (out_graphemes)

输出

1,e,g,I,r,l,1,a,3,r,ea,d,2

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53255085

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档