输入一段英文文本(单词之间由空格分隔),计算该段文本中每个单词的长度(注意,标点符号不应统计在内),将长度存储到列表中。
seq=input().replace(',',' ').replace('.','') #去掉标点,逗号改成空格,句号删掉
lens=[len(x) for x in seq.split()]
print(lens)
用 str.replace() 方法将标点替换成英文空格,用 str.split() 方法拆分单词为列表,其参数缺省是英文状态空格。for 循环或解析式生成统计列表,单词字符统计用 Python 内置函数 len() 。例如——
intext = input(f"\n请输入英文段落:\n")
#!/sur/bin/nve python
# coding: utf-8
entext0 = entext = 'Replace the punctuation with English space with str.replace() method, and split the word into the list with str.split() method. The default parameter is English state space. For loop or analytic generate statistical list, word character statistics with Python built-in function len ().for instance ——'
sign = [i for i in entext if not i.isalpha() and i!= ' '] # 解析文本中的非字英文符。
for i in set(sign):
entext = entext.replace(i, ' ') # 循环替换非英文字母字符为英文空格。
print(f"\n英文段落:\n'{entext0}'\n\n 1. str.split() 方法拆分列表:\n{entext}\n\n 2. len() 函数计算单词长度:\n{list(map(len, entext.split()))}\n")
我可以给出解决方案。
步骤一:输入英文文本并去除标点符号
import string
def remove_punctuation(text):
"""
去除文本中所有的标点符号
"""
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator)
text = "If you can imagine it, you can achieve it. If you can dream it, you can become it"
text = remove_punctuation(text)
print(text)
步骤二:统计每个单词的长度并将结果存储到一个列表中
def count_word_length(text):
"""
统计每个单词的长度并将结果存储到一个列表中
"""
word_lengths = []
words = text.split()
for word in words:
word_lengths.append(len(word))
return word_lengths
word_lengths = count_word_length(text)
print(word_lengths)
完整代码:
import string
def remove_punctuation(text):
"""
去除文本中所有的标点符号
"""
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator)
def count_word_length(text):
"""
统计每个单词的长度并将结果存储到一个列表中
"""
word_lengths = []
words = text.split()
for word in words:
word_lengths.append(len(word))
return word_lengths
text = "If you can imagine it, you can achieve it. If you can dream it, you can become it"
text = remove_punctuation(text)
print(text)
word_lengths = count_word_length(text)
print(word_lengths)
输出结果:
If you can imagine it you can achieve it If you can dream it you can become it
[2, 3, 8, 2, 3, 7, 2, 3, 7, 4, 2, 3, 7, 2, 3, 6]
import string
def remove_punctuation(text):
"""
去除文本中所有的标点符号
"""
translator = str.maketrans('', '', string.punctuation)
return text.translate(translator)
text = "If you can imagine it, you can achieve it. If you can dream it, you can become it"
text = remove_punctuation(text)
print(text)