所以我在写一段代码,计算#ed的单词数量,如果一个单词没有#ed,它就会忽略它。
当我运行这段代码的时候,我输入#Python是#AWESOME!
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是#awesome!
它输出#awesome 1,但没有#python 1。
我需要它输出所有#ed单词,并统计使用了多少个。我认为问题是由string.punctuation引起的。
这可能会对你有用
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])
你说对了一部分!
.strip(string.punctuation)
是罪魁祸首。
根据... Python文档, #是string.punctuation-set的一部分。
同样来自 Python文档关于 strip
-function.string.strip(s[, chars])
string.strip(s[, chars])
返回去掉前导符和尾部字符的字符串副本。如果省略chars或None,则删除空白字符。如果给定而不是None,则chars必须是一个字符串;字符串中的字符将从本方法调用的字符串的两端被剥离。
因此,你将删除前导符(例如第一个)#和保存在变量中的字符串。line
是 "python is #awesome"
.你的while-loop也将永远不会退出,如 ".".strip(string.punctuation) == ""
.看来你是真的不想要 .strip
-方法在那里。如果只在最后一个字符是标点符号的情况下才删除,则使用 "your string".rstrip(string.punctuation)
而是