所以我正在写一个代码来计算#ed的字数,如果一个单词不是#ed,它就会忽略它。
当我运行代码时:
import string
all = []
count = {}
word = []
line = input("Tweet: ").lower().strip(string.punctuation)
while line != '':
word.extend(line.split())
line = input("Tweet: ").lower().strip(string.punctuation)
for w in word:
if w.startswith('#'):
count[w] = count.get(w, 0) + 1
for word in sorted(count):
print(word, count[word])我输入#Python是#太棒了!
它输出#可怕的1,但没有#python 1
我需要它输出所有#ed字,并计算使用了多少。我认为这个问题是由string.punctuation引起的。
发布于 2020-05-05 09:34:37
这可能会对你有用
import string
all = []
count = {}
word = []
line = input("Tweet: ").lower().rstrip(string.punctuation)
while line != '.':
word.extend(line.split())
line = input("Tweet: ").lower().rstrip(string.punctuation)
for w in word:
if w.startswith('#'):
count[w] = count.get(w, 0) + 1
for word in sorted(count):
print(word, count[word])或
import string
all = []
count = {}
word = []
line = input("Tweet: ").lower()
while line != '.':
word.extend(line.split())
line = input("Tweet: ").lower()
for w in word:
if w.startswith('#'):
w = w.rstrip(string.punctuation)
count[w] = count.get(w, 0) + 1
for word in sorted(count):
print(word, count[word])发布于 2020-05-05 09:33:20
你说的部分是对的!
.strip(string.punctuation)是罪魁祸首
根据Python文档的说法,#是字符串.标点符号集的一部分。
也来自Python文档,在strip-function上:
string.strip(s,chars) 返回字符串的副本,并删除前导字符和尾随字符。如果省略字符或无字符,则删除空白字符。如果给定而不是空,则字符必须是字符串;字符串中的字符将从调用此方法的字符串的两端剥离。
因此,您正在删除前导(例如,第一个)#,而保存在变量line中的字符串是"python is #awesome"。同时循环也永远不会退出,就像".".strip(string.punctuation) == ""一样。看起来你真的一点也不想要.strip-methods。如果仅当最后一个字符是标点符号时才删除它,则使用"your string".rstrip(string.punctuation)代替。
https://stackoverflow.com/questions/61609753
复制相似问题