Python从文本文件创建图书索引

Python从文本文件创建图书索引,python,python-3.x,Python,Python 3.x,我有一个文本文件,可能看起来像这样 3:degree 54:connected 93:adjacent 54:vertex 19:edge 64:neighbor 72:path 55:shortest path 127:tree 3:degree 55:graph 64:adjacent and so on.... 我想让我的函数读取每行文本,然后在冒号处将其拆分成一个字典,其中单词位于“键”位置,页码位于字典的“值”位置-然后我必须创建一个新字典并扫描每个单词,如果它已经在字典中,只需

我有一个文本文件,可能看起来像这样

3:degree
54:connected
93:adjacent
54:vertex
19:edge
64:neighbor
72:path
55:shortest path
127:tree
3:degree
55:graph
64:adjacent   and so on....
我想让我的函数读取每行文本,然后在冒号处将其拆分成一个字典,其中单词位于“键”位置,页码位于字典的“值”位置-然后我必须创建一个新字典并扫描每个单词,如果它已经在字典中,只需在后面添加页码,如果它不在字典中,我会把它加到字典里

这是我到目前为止的想法

def index(fileName):

    inFile=open(fileName,'r')
    index={}
    for line in inFile:
        line=line.strip()      #This will get rid of my new line character
        word=line[1]
        if word not in index:
            index[word]=[]
            index[word].append(line)
    return index

fileName='terms.txt'

print(index(fileName))

我在正确的页面上,但只是需要一点帮助才能开始

编辑我用
#Edit

def index(fileName):
    inFile=open(fileName,'r')
    index={}
    for line in inFile:
        line=line.strip().split(':',1) # edit
        word,index=line # edit
        if word not in index:
            index[word]=[]
        index[word].append(index) # edit
    return index

您没有分割线,您只是在位置1处提取角色

使用
.split(“:”,1)
上拆分行一次:

def index(filename):
    with open(filename) as infile:
        index = {}
        for line in infile:
            page, word = map(str.strip, line.split(':', 1))
            index.setdefault(word, []).append(int(page))
        return index
您可能希望使用集合,以避免相同的页码被添加两次。您还可以使用
collections.defaultdict
进一步简化此操作:

from collections import defaultdict

def index(filename):
    with open(filename) as infile:
        index = defaultdict(set)
        for line in infile:
            page, word = map(str.strip, line.split(':', 1))
            index[word].add(int(page))
        return index
这使得:

defaultdict(<type 'set'>, {'neighbor': set([64]), 'degree': set([3]), 'tree': set([127]), 'vertex': set([54]), 'shortest path': set([55]), 'edge': set([19]), 'connected': set([54]), 'adjacent': set([64, 93]), 'graph': set([55]), 'path': set([72])})
defaultdict(,{'neighbor':set([64]),'degree':set([3]),'tree':set([127]),'vertex':set([54]),'shortest path':set([55]),'edge':set([19]),'connected':set([54]),'neighbor':set([64,93]),'graph':set([55]),'path':set([72]))

用于输入文本;
defaultdict
dict
的子类,其行为与普通字典类似,只是它会为您尝试访问但尚未出现的每个键创建一个新的
集。

您可以使用
str.split
将字符串分隔为标记。在您的情况下,分隔符是

records = """3:degree
     54:connected
     93:adjacent
     54:vertex"""
index = {}
for line in records.split('\n'):
     page, word = line.split(':')
     index[word] = int(page.strip())

index
# {'vertex': 54, 'connected': 54, 'adjacent': 93, 'degree': 3}
在某些时候,您需要处理具有多个页面引用的单词。为此,我建议创建一个
collections.defaultdict
,默认设置为
list

from collections import defaultdict
index = defaultdict(list)
index[word].append(page)  # add reference to this page

使用
index.setdefault
将if-else条件缩短为一行。您看过这个吗,?方法类似。非常感谢-我想添加一行,将所有大写字母转换为小写字母-我是否必须将其转换为字符串以将其转换为小写字母,然后转换为列表以按字母顺序排序?d=str(索引)表示d:element.lower()中的元素#像这样的东西有用吗?不要把
索引
变成字符串,它是字典。我不确定你在这里想要实现什么
index[word.lower()].add(int(page))
将存储以小写字母开头的单词。若要按排序顺序(按键)循环
index
,请对排序(index)中的单词使用