【发布时间】:2019-03-30 15:59:53
【问题描述】:
我需要知道如何计算列表中以字母 A、B、C .. Z 开头的单词数。
这里我留下txt文件的阅读部分
#!/usr/bin/python
def main():
lines = []
xs = []
try:
with open("bin-nombres.txt", 'r') as fp:
lines = [lines.strip() for lines in fp]
for i in lines:
print(i[0])
xs = counterByLetter(i[0])
print(xs)
except EOFError as e:
print(e)
finally:
pass
def counterByLetter(data):
return [(k, v) for k, v in {v: data.count(v) for v in 'abcdefghijklmnopqrstuvwxyz'}.items()]
if __name__ == "__main__":
main()
我必须计算以 [A ... Z] 开头的单词数。例如。
- 以A开头的单词有3个。
- 以B开头的单词有20个。
- 等等..
在这里,我将解决问题的方法。感谢帮助过我的人!!
import string
def main():
try:
# this initiates the counter with 0 for each letter
letter_count = {letter: 0 for letter in list(string.ascii_lowercase)}
with open("bin-nombres.txt", 'r') as fp:
for line in fp:
line = line.strip()
initial = line[0].lower()
letter_count[initial] += 1 # and here I increment per word
#iterating over the dictionary to get the key and the value.
#In the iteration process the values will be added to know the amount of words.
size = 0
for key , value in letter_count.items():
size += value
print("Names that start with the letter '{}' have {} numbers.".format(key , value))
print("Total names in the file: {}".format(size))
except EOFError as e:
print(e)
if __name__ == "__main__":
main()
【问题讨论】:
-
看起来你的
main应该是一个函数,而不是一个类。 -
是的,对不起
-
您的文件数据怎么样?到目前为止,除了读取文件的内容之外,您还尝试过什么?
-
现在我正在试验 xs = list (filter (lambda x: x [0] == 'a', lines)) 看看以后我是否可以创建一个元组,以便我有类似的东西 ('a', 4), ('b', 1)
-
对于txt,每一行只有一个单词。是的,它已经按字母顺序排列了。