我正在尝试编写一个程序,它给出了给定字符串中所有元音的count()和索引,并将其存储在字典中。到目前为止,这就是我所拥有的:
txt = "Text sample for vowel counting and indexing"
def ProcText(char,texto):
lst_count=[]
char_count = texto.count(str(char))
lst_count.append(char_count)
print(lst_count)
lst_ind=[]
char_ind = [i for (i,x) in enumerate(texto) if x == str(char)]
lst_ind.append(char_ind)
print(lst_ind)
ProcText("a",txt)
[2]
[[6, 31]]
所以在字典中我希望每个元音都有这样的东西:
{'a count' : 2 , 'a index' : 6,31}
有没有Python允许这种情况发生?使用Python 3.6
答案 0 :(得分:0)
除了已收到的评论之外:count方法无论如何都会遍历你的句子,但你可以用更简单的方式做同样的事情,因为索引的数量会给你出现次数。怎么样:
txt = "Text sample for vowel counting and indexing"
vowel = "a"
vowel_dict = {}
def proc_text(char,texto):
char_ind = [i for (i,x) in enumerate(texto) if x == char]
return (len(char_ind), char_ind)
result = (proc_text(vowel,txt))
vowel_dict[str(vowel) + " count"] = result[0]
vowel_dict[str(vowel) + " indices"] = result[1]
print(my_dict)
因为你可以使用Python返回一个元组,允许你返回多个对象。我相信你可以按照abarnert的建议,以更简洁的方式重构这个以实现你想要的东西。
答案 1 :(得分:0)
您可以使用以下两个步骤来执行列表推导:
indexes = [(v,[ i for i,c in enumerate(txt) if c == v]) for v in "aeiou" ]
vDict = dict( [("%s index"%v,a) for v,a in indexes] + [("%s count"%v,len(a)) for v,a in indexes] )
# dict == {'a index': [6, 31], 'e index': [1, 10, 19, 38], 'i index': [27, 35, 40], 'o index': [13, 17, 23], 'u index': [24], 'a count': 2, 'e count': 4, 'i count': 3, 'o count': 3, 'u count': 1}
但是我相信你会发现你的字典中的键的选择可能很难在之后使用。我会建议一个字母作为键和索引列表作为值。对于任何给定的字母,您可以使用索引列表上的len()轻松获取计数。
vDict = { v:[ i for i,c in enumerate(txt) if c == v] for v in "aeiou" }
# vDict = {'a': [6, 31], 'e': [1, 10, 19, 38], 'i': [27, 35, 40], 'o': [13, 17, 23], 'u': [24]}
即使字符串不包含任何元音(即空索引列表),这也会为字典中的每个元音提供一个条目
如果您只想要字符串中实际存在的字母,则可以执行以下操作:
cDict = { k:[ i for i,c in enumerate(txt) if c == k] for k in set(txt) }
这将为字典中的条目仅提供实际存在的字母。然后,您可以根据需要过滤元音上的键(或仅限辅音)。
答案 2 :(得分:0)
感谢您的回复,但我能够找到自己的解决方案,我将在此分享,希望将来能帮助其他人。
目标是计算字符串中的所有元音(大写和小写没有区别),并且还要说明这些元音的索引。所有这些信息都必须存储在字典中。
所以我定义了一个函数来计算字符串中的所有元音:
def ProcVogalCount(texto):
texto = texto.lower()
vogal = ["a","e","i","o","u"]
lst_count = []
for i in vogal:
c = texto.count(i)
lst_count.append(c)
return(lst_count)
后面是另一个指定每个元音的索引的函数:
def ProcVogalInd(texto):
texto = texto.lower()
vogal = ["a","e","i","o","u"]
lst_ind = []
for i in vogal:
indices = [a for (a,b) in enumerate(texto) if b == i]
lst_ind.append(indices)
return(lst_ind)
最后,我创建了最后一个函数,该函数获取其他两个函数返回的列表,并将所有内容压缩为两个单独的字典:
def DicionarioVogais(texto):
lst1 = ProcVogalCount(texto)
keys1 = ['A cont:','E cont:','I cont:','O cont:','U cont:']
dic1 = dict(zip(keys1,lst1))
lst2 = ProcVogalInd(texto)
keys2 = ['A ind:','E ind:','I ind:','O ind:','U ind:']
dic2 = dict(zip(keys2,lst2))
print(dic1)
print(dic2)
因此,在字符串上调用最后一个函数的最终结果是:
{'A cont:': 6, 'E cont:': 13, 'I cont:': 5, 'O cont:': 4, 'U cont:': 3} {'A ind:': [0, 30, 35, 38, 44, 76], 'E ind:': [6, 9, 12, 18, 20, 24, 48, 53, 56, 58, 63, 70, 73], 'I ind:': [3, 45, 50, 65, 68], 'O ind:': [15, 27, 42, 77], 'U ind:': [2, 34, 62]}