python中的词典生成

python中的词典生成,python,Python,我正试着读一段文章,并用这段文章编一本字典。键是单词,值是行号。以下是我的代码: import string def build_word_index(): input_file=(input('file name: ')) input_file_open=open(input_file,'r') word_map = {} line_no = 0 w=[] for line in input_file_open: word_

我正试着读一段文章,并用这段文章编一本字典。键是单词,值是行号。以下是我的代码:

import string
def build_word_index():
    input_file=(input('file name: '))
    input_file_open=open(input_file,'r')

    word_map = {}
    line_no = 0
    w=[]

    for line in input_file_open:

        word_lst = line.strip().split()

        word_lst = [w.lower().strip(string.punctuation) for w in word_lst]

        w.append(word_lst)           

        for word in w[line_no]:
            if word!="":
                word_map[word]=line_no
        line_no+=1

    print(word_map)

    index_lst = sorted(list(word_map.items()))
    print(index_lst)

    for word, line_set in index_lst:
        line_lst = sorted(list(line_set))
        line_str = str( line_lst[0] )
        for line_no in line_lst[1:]:
            line_str += ", {}".format( line_no )
        print("{:14s}:".format(word), line_str )



    input_file_open.close()

build_word_index()
我得到的错误是: 错误:

回溯(最近一次呼叫最后一次):
文件“C:/Users/Dasinator/Documents/Books IX/Python Examples/textute Examples/lab10/lab10d.py”,第39行,在
建立单词索引()
文件“C:/Users/Dasinator/Documents/Books IX/Python Examples/textute Examples/lab10/lab10d.py”,第29行,在build\u word\u索引中
行列表=已排序(列表(行集合))
TypeError:“int”对象不可编辑

我想知道,是否有人可以看看我的代码,给我一些关于修复这个错误的提示。谢谢

您的列表
索引是调用dict的
items
方法的产物,该方法将为您提供包含其键和值的
元组的
列表

>>> d = {'a': 1, 'b': 2}
>>> d.items()
dict_items([('b', 2), ('a', 1)])
当您按原样迭代时,第一个标识符命名当前键,第二个标识符命名循环的当前值:

>>> for a, b in d.items():
...     print("a: {}, b: {}".format(a, b))
... 
a: b, b: 2
a: a, b: 1
>>> # Notice the keys are unsorted!
在循环的下一行,您尝试将第二个标识符
line\u set
传递给
list
构造函数,该构造函数从任何支持迭代的内容中生成一个列表

line_lst = sorted(list(line_set))
# Hint: this is referenced in your error message
但是
line_lst
不是一个可移植的对象!它只是一个普通整数(
int
),因此Python放弃了:

TypeError: 'int' object is not iterable

据我所知,您需要每个单词的行列表,而不仅仅是遇到该单词的最后一行。如果是这样的话,
word\u映射应该是从单词到行号列表的映射,而不仅仅是到单个数字的映射。因此,为单词添加行号的行现在是
word\u map[word]+=[line\u no]
。如果单词不在word\u map:word\u map[word]=[]
部分,则使用
defaultdict
而不是简单的字典来避免编写

以下是一个工作版本:

import string, collections
def build_word_index():
    input_file=(input('file name: '))
    input_file_open=open(input_file,'r')

    word_map = collections.defaultdict (list)
    line_no = 0
    w=[]

    for line in input_file_open:

        word_lst = line.strip().split()

        word_lst = [w.lower().strip(string.punctuation) for w in word_lst]

        w.append(word_lst)           

        for word in word_lst:
                word_map[word]+=[line_no]
        line_no+=1

    print(word_map)

    index_lst = sorted(list(word_map.items()))
    print(index_lst)

    for word, line_set in index_lst:
        line_lst = sorted(list(line_set))
        line_str = str( line_lst[0] )
        for line_no in line_lst[1:]:
            line_str += ", {}".format( line_no )
        print("{:14s}:".format(word), line_str )



    input_file_open.close()

build_word_index()
输入示例:

one two
three three four
one two four
four three
示例输出:

file name: defaultdict(<class 'list'>, {'one': [0, 2], 'three': [1, 1, 3], 'two': [0, 2], 'four': [1, 2, 3]})
[('four', [1, 2, 3]), ('one', [0, 2]), ('three', [1, 1, 3]), ('two', [0, 2])]
four          : 1, 2, 3
one           : 0, 2
three         : 1, 1, 3
two           : 0, 2
文件名:defaultdict(,{'one':[0,2],'three':[1,1,3],'two':[0,2],'four':[1,2,3])
[(‘四’,[1,2,3]),(‘一’,[0,2]),(‘三’,[1,1,3]),(‘二’,[0,2])]
四:1,2,3
一:0,2
三:1,1,3
二:零,二,

已经回答了,但我的看法是这样的。我还没有尝试过这个代码,但我认为它应该可以工作

from collections import defaultdict
import re

def build_word_index(filename):
    word_index = defaultdict(list)

    with open(filename,'rb') as word_file:
        for i, line in enumerate(word_file):
            line = line.strip().lower()
            for word in line.split():
                word_index[word].append(i)

    for word in sorted(word_index):
        print word + ': ' + ', '.join(map(str,word_index[word]))

    return dict(word_index)

错误发生在哪一行?这将有助于解决您的问题。如果发现了行错误,应使用该信息创建一个。已编辑的“我的问题”以包含完整的错误报告。希望有帮助。我看到您的代码中有一些
打印
语句。特别是,在您的跑步中,
print(index_lst)
的输出是什么?感谢您的帮助。谢谢你可能想看雷蒙德·赫廷格的这段视频。
from collections import defaultdict
import re

def build_word_index(filename):
    word_index = defaultdict(list)

    with open(filename,'rb') as word_file:
        for i, line in enumerate(word_file):
            line = line.strip().lower()
            for word in line.split():
                word_index[word].append(i)

    for word in sorted(word_index):
        print word + ': ' + ', '.join(map(str,word_index[word]))

    return dict(word_index)