我有一段文字,我用图形符号把不同的声音分开。这些图形符号现在是列表的一部分,如下所示:
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])。我怎样才能获得我感兴趣的职位,并在必要时更换它们?
另外,我也不确定我访问字典和替换图形符号的方式是否正确。
发布于 2018-11-12 02:40:33
使用Python的理解
试试这个:
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
https://stackoverflow.com/questions/53255085
复制相似问题