首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >string.punctuation删除值

string.punctuation删除值
EN

Stack Overflow用户
提问于 2020-05-05 09:19:07
回答 2查看 53关注 0票数 0

所以我正在写一个代码来计算#ed的字数,如果一个单词不是#ed,它就会忽略它。

当我运行代码时:

代码语言:javascript
复制
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引起的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-05 09:34:37

这可能会对你有用

代码语言:javascript
复制
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])

代码语言:javascript
复制
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])
票数 1
EN

Stack Overflow用户

发布于 2020-05-05 09:33:20

你说的部分是对的!

代码语言:javascript
复制
.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)代替。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61609753

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档