我写了这个函数:
def make_upper(words):
for word in words:
ind = words.index(word)
words[ind] = word.upper()
我还写了一个函数来计算每个字母出现的频率:
def letter_cnt(word,freq):
for let in word:
if let == 'A': freq[0]+=1
elif let == 'B': freq[1]+=1
elif let == 'C': freq[2]+=1
elif let == 'D': freq[3]+=1
elif let == 'E': freq[4]+=1
答案 0 :(得分:0)
如果您想使用lambda
将列表中的字符串转换为大写字母,则可以将其与map()
一起用作:
>>> words = ["Hello", "World"]
>>> map(lambda word: word.upper(), words) # In Python 2
['HELLO', 'WORLD']
# In Python 3, use it as: list(map(...))
地图(功能,可迭代,......)
将函数应用于iterable的每个项目并返回结果列表。
要查找单词中每个字符的频率,您可以使用collections.Counter()
(子类dict
类型):
>>> from collections import Counter
>>> my_word = "hello world"
>>> c = Counter(my_word)
# where c holds dictionary as:
# {'l': 3,
# 'o': 2,
# ' ': 1,
# 'e': 1,
# 'd': 1,
# 'h': 1,
# 'r': 1,
# 'w': 1}
Counter是用于计算可哈希对象的dict子类。它是一个无序集合,其中元素存储为字典键,它们的计数存储为字典值。
答案 1 :(得分:0)
对于字母计数,不要重新发明轮子collections.Counter
Counter是用于计算可哈希对象的dict子类。它是一个无序集合,其中元素存储为字典键,其计数存储为字典值。计数允许为任何整数值,包括零或负计数。 Counter类与其他语言的包或多重集类似。
答案 2 :(得分:0)
使用字典计算字母频率会更有效,是的。请注意,您手动为每个字母排列一个数字(" A" 0,等等)。如果我们能够将一个字母与其出现的次数直接关联起来,而不在其间添加一组额外的数字,那会不会更容易?
考虑代码:
freq = {"A":0, "B":0, "C":0, "D":0, ... ..., "Z":0}
for letter in text:
freq[letter] += 1
此字典用于比当前代码更有效地计算频率。您只需在每次看到给定字母的条目中添加一个。
我还要提到您可以使用某些库有效地计算频率。如果您对分析频率感兴趣,请查看collections.Counter()以及collections.Counter.most_common()方法。
无论你是否决定只使用collections.Counter(),我都会尝试学习字典在这种情况下有用的原因。
最后一点说明:我个人发现输入" freq"的值。字典很乏味。如果您愿意,可以使用以下代码构建一个空字母的字母:
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
freq = {letter:0 for letter in alphabet}
答案 3 :(得分:0)
def punc_remove(words):
for word in words:
if word.isalnum() == False:
charl = []
for char in word:
if char.isalnum()==True:
charl.append(char)
ind = words.index(word)
delimeter = ""
words[ind] = delimeter.join(charl)
def letter_cnt_dic(word,freq_d): 换言之: freq_d [let] + = 1
导入字符串 def letter_freq(fname): fhand = open(fname) freqs = dict() alpha = list(string.uppercase [:26]) for let in alpha:freqs [let] = freqs.get(let,0)
for line in fhand:
line = line.rstrip()
words = line.split()
punc_remove(words)
#map(lambda word: word.upper(),words)
words = [word.upper() for word in words]
for word in words:
letter_cnt_dic(word,freqs)
fhand.close()
return freqs.values()
答案 4 :(得分:-1)
您可以阅读有关Counter和List Comprehensions的文档,或将其作为小型演示版运行:
from collections import Counter
words = ["acdefg","abcdefg","abcdfg"]
#list comprehension no need for lambda or map
new_words = [word.upper() for word in words]
print(new_words)
# Lets create a dict and a counter
letters = {}
letters_counter = Counter()
for word in words:
# The counter count and add the deltas.
letters_counter += Counter(word)
# We can do it to
for letter in word:
letters[letter] = letters.get(letter,0) + 1
print(letters_counter)
print(letters)