Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中创建一个列表,其中包含单词的长度和计数_Python - Fatal编程技术网

在python中创建一个列表,其中包含单词的长度和计数

在python中创建一个列表,其中包含单词的长度和计数,python,Python,我有一个家庭作业,其中我必须定义一个函数,该函数要求用户输入一个段落,并创建一个列表列表(例如[[x,y],[x1,y2],[x3,y3]),其中x=字符串中一个单词的指定长度,y=指定长度的单词计数。(例如[[1,2],[2,3],[4,4],[6,1]]…1表示1个字母单词,2表示1个字母单词的计数,依此类推。) 这就是我目前拥有的: def wordCount(): words = [] wordCount_text_length = [] word_count = []

我有一个家庭作业,其中我必须定义一个函数,该函数要求用户输入一个段落,并创建一个列表列表(例如[[x,y],[x1,y2],[x3,y3]),其中x=字符串中一个单词的指定长度,y=指定长度的单词计数。(例如[[1,2],[2,3],[4,4],[6,1]]…1表示1个字母单词,2表示1个字母单词的计数,依此类推。)

这就是我目前拥有的:

def wordCount():
   words = []
   wordCount_text_length = []
   word_count = []

   text = input('Please enter a paragaph of regular English text: \n')
   words = (text.split())

   for x in words:
       wordCount_text_length.append(len(x))

   for y in wordCount_text_length:
       word_count.append(wordCount_text_length.count(y))
当我在控制台中运行并使用短语“我看到了一只蓝鸟”时,将打印以下内容(变量供参考):

我被卡住了,因为1.)它将标点符号作为字符串的一部分进行计数。2.)如何创建循环以创建列表列表,这些列表将采用单词长度/计数一次,然后移动到下一个长度?

您可以使用
.isalpha()
过滤掉标点符号:

text = input('Please enter a paragaph of regular English text: \n').split()
new_text = [''.join(b for b in i if b.isalpha()) for i in text]
final_list = [[len(i), ''.join(new_text).count(i.lower())] for i in new_text]
使用“我看见一只蓝色的鸟”的输入,最终输出为:

[[1, 1], [3, 1], [1, 2], [4, 1], [4, 1]]
您还可以使用字典帮助可视化您的输出:

final_list = {i.lower():[len(i), ''.join(new_text).count(i.lower())] for i in new_text}
输出:

{'i': [1, 1], 'saw': [3, 1], 'a': [1, 2], 'blue': [4, 1], 'bird': [4, 1]}

我使用了一个dict,然后在末尾将其转换为一个列表。如果希望对最终列表进行排序,我还使用最后一行中的.isalpha().
sorted(word\u length.items())
检查标点符号

words = input().split()
word_lengths = {}
puncs = [',', '.']
for word in words:
    y = word
    if not y.isalpha(): y = y[:-1]
    length = len(y)
    try: word_lengths[length] += 1
    except KeyError: word_lengths[length] = 1
print([[k, v] for k, v in word_lengths.items()])

1) 查看每个字符-如果不是字母,请不要计数(追加)它。我在for循环中使用y作为长度列表中每个int的变量。2)我第一次误读了这一部分。想想如果你没有电脑,你会如何手动计数和跟踪计数。记下这个过程。比如,你可能会在列表中计算1个字母的单词数。然后再看一次列表n计算两个字母单词的数量等。有更有效的方法。但这始终是开始构思算法的好方法。然后将该过程转化为代码。从快速而肮脏的解决方案开始,然后在必要时进行优化,以便更好地理解问题解决方案。
words = input().split()
word_lengths = {}
puncs = [',', '.']
for word in words:
    y = word
    if not y.isalpha(): y = y[:-1]
    length = len(y)
    try: word_lengths[length] += 1
    except KeyError: word_lengths[length] = 1
print([[k, v] for k, v in word_lengths.items()])