import string p = string.punctuation s = input(">>>").split() s = [i[:-1] if i[-1] in p else i for i in s ] for i in s: print(i) --result >>>Why this word does this, I haven't got a clue. Why this word does this I haven't got a clue
时间: 2024-03-15 20:42:51 浏览: 19
这段代码的作用是将用户输入的字符串按照空格分割成单词,并去掉每个单词末尾的标点符号(如果有的话),然后逐个打印出来。在打印的过程中,每个单词之间不会添加任何符号或空格。
对于输入的字符串“Why this word does this, I haven't got a clue.”,程序的输出是:
Why
this
word
does
this
I
haven't
got
a
clue
相关问题
import string sent = input().strip() for c in string.punctuation: sent = sent.replace(c," ") #1去除标点符号 wordlist = sent.split() #分词 wordcounts = {} wordlens =[] for word in wordlist: wordcounts[word] = wordcounts.get(word,0) + 1 #2词频统计 for word in wordcounts.keys(): wordlens.append((word,len(word))) #计算每个单词长度 sort_wordcounts = sorted(wordcounts,key = lambda x:x[1],reverse =True) #3按照词频排序 sort_wordlens = sorted(wordlens,key = lambda x:x[1],reverse=True) #4按照单词长度排序 maxlen = len(sort_wordlens[0]) #5最长单词的长度 for wlen in sort_wordlens: #6输出所有最长单词 if wlen == maxlen: print("maxlen:{1:<3}word:{0:>10}".format(word,wlen)) else: print() #7 for word, count in sort_wordcounts: #输出单词词频 print("{0:<10}{1:->5}".format(word,count)) #8
这段代码的功能是输入一段文本,去除标点符号并进行分词,统计每个单词出现的次数,按照单词出现的次数和单词长度进行排序,输出最长的单词和每个单词的出现次数。具体的代码实现如下:
1. 使用 for 循环遍历 string.punctuation 中的标点符号,使用 replace 方法将标点符号替换为空格。
2. 使用字典 wordcounts 统计每个单词出现的次数,如果字典中已经存在该单词,则将其出现次数加 1。
3. 使用 sorted 函数按照单词出现的次数进行排序,将排序后的结果存储在 sort_wordcounts 中。
4. 使用 sorted 函数按照单词长度进行排序,将排序后的结果存储在 sort_wordlens 中。
5. 计算最长单词的长度,将其存储在 maxlen 变量中。
6. 遍历 sort_wordlens 中的每个单词,如果其长度等于最长单词的长度,则输出该单词。
7. 遍历 sort_wordcounts 中的每个单词,输出单词和出现次数。
8. 程序运行结束。
import string mafo = input() for i in string.punctuation: mafo = mafo.replace(i, " ") mafoi = mafo.split() print(mafoi)代码能实现输入一个英文句子,以回车符结束,单词间以空格分隔,标点符号后跟至少一个空格,统计并输出单词的个数(仅统计单词,数字按单词计,不计算标点符号,重复单词出现几次就统计几次)。功能吗
以下是代码实现:
```python
import string
mafo = input()
for i in string.punctuation:
mafo = mafo.replace(i, " ")
mafoi = mafo.split()
count = {}
for word in mafoi:
if word in count:
count[word] += 1
else:
count[word] = 1
print(len(count))
```
解释:
首先,通过 `input()` 函数获取用户输入的句子。
然后,使用 `string.punctuation` 模块获取所有的标点符号,并将其替换为空格。这样,所有标点符号后面的空格都会被替换为一个空格,方便后面的分割操作。
使用 `split()` 函数将句子按空格分割,得到单词列表 `mafoi`。
接下来,使用一个字典 `count` 来统计每个单词出现的次数。遍历单词列表 `mafoi`,如果单词已经在字典 `count` 中,则将其出现次数加 1;否则,在字典中新增一个键值对,键为单词,值为 1。
最后,输出字典 `count` 的长度,即为单词的个数。注意,字典 `count` 中的每个键都是不重复的,因此字典的长度就是单词的个数。