Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.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,问题就在这里 定义一个函数make_length_wordcount(),该函数: 将输入作为当前目录中的文件名(作为字符串) 返回一个字典,其中每个关键字都是单词长度,其值是具有该长度的单词数 例如,如果输入文件的文本是“Hello Python people Welcome to the world of Python”,那么字典应该是: {2:2,3:1,5:2,6:3,7:1} 以下是我目前掌握的情况: def make_length_wordcount(x): filena

问题就在这里

  • 定义一个函数make_length_wordcount(),该函数:
  • 将输入作为当前目录中的文件名(作为字符串)
  • 返回一个字典,其中每个关键字都是单词长度,其值是具有该长度的单词数
  • 例如,如果输入文件的文本是“Hello Python people Welcome to the world of Python”,那么字典应该是: {2:2,3:1,5:2,6:3,7:1}
以下是我目前掌握的情况:

def make_length_wordcount(x):
    filename=x+'.txt'
    infile=open(filename)
    wordlist=infile.read().split()
    counter1={}
    for word in wordlist:
        if word in counter1:
            counter1[len(word)]+=1
        else:
            counter1[len(word)]=1

    infile.close()
    print(counter1)
我在某个地方缺少一个for循环来实际添加到计数器。不过我想不出来。任何帮助都将不胜感激

以下是我的输出:

{2: 1, 3: 1, 5: 1, 6: 1, 7: 1}
只需使用len和dict进行计数:

在您自己的代码中,遵循相同的逻辑,忘记要计算长度的单词:

with open("yourfile") as f:
    counter1 = {}
    for line in f:
        # map(len,["foo","foobar","barf"]) -> 3, 6, 4
        for ln in map(len, line.split()):
            if ln in counter1:
                counter1[ln] += 1
            else:
                counter1[ln] = 1

print(counter1)

你不是在计算单词出现的次数,而是在计算特定长度的单词出现的次数。

你从Padraic得到了更好的答案,但你版本中唯一的错误是你在字典中检查了单词,而不是它的长度

def make_length_wordcount(x):
    filename=x+'.txt'
    infile=open(filename)
    wordlist=infile.read().split()
    counter1={}
    for word in wordlist:
        if len(word) in counter1:
            counter1[len(word)]+=1
        else:
            counter1[len(word)]=1
    infile.close()
    print(counter1)

以下是我的工作答案:

def make_length_wordcount():
    test = " Hello World\n This is some cool python"
    wordlist=test.split()
    words = {}
    for word in wordlist:
        if str(len(word)) in words.keys():
            words[str(len(word))] = words[str(len(word))] + 1
        else:
            words[str(len(word))] = 1
    result = ""
    for key in sorted(words.iterkeys()):
        result = result + "%s: %s, " % (key, words[key])
    result = result[:len(result)-2]
    print result

make_length_wordcount()
运行:

python test.py 
2: 1, 4: 3, 5: 2, 6: 1

我们能看到你的程序的输出吗?刚刚为你添加了它。我使用的是与示例完全相同的文件,我的输出应该匹配。它没有计算每个单词。在计数器1中将if语句更改为
len(word)。这样做了。谢谢@OisinI将在您的答案中添加打开文件代码(使用with语句)以获得完整性我感谢@Padraic Cunningham的帮助!我仍在学习,只是在做基础。我不知道如何使用
集合。计数器
@Tabzzy。。我已经添加了指向
计数器
对象的链接,请检查并学习如何使用它们
collections
模块非常适合学习使用…@Tabzzy,第二个示例基本上使用了您自己的逻辑,它只是使用map获取每个单词的长度并按行拆分,而不是一次读取整个文件并拆分为一个大列表,收集。计数器是做你想做的事情的惯用方法,但我知道这是一个学习练习。@IronFist,干杯,就要看《工作狂》了,然后就开始干了;)正如我提到的,我不熟悉
集合。Counter
。我仍然在学习Python。这是我高中以来的第一门编码课程。仍在努力进入最佳状态。我的教授更喜欢这样写我们的代码。
python test.py 
2: 1, 4: 3, 5: 2, 6: 1