从文本文件中按行号索引单词

时间:2016-11-20 20:32:20

标签: python dictionary text indexing python-3.4

所以我的作业问题是从文本文件中获取函数lineIndex索引词,并返回文本文件中每个单词的行号列表。整个输出必须在字典中返回。

例如,这里是文本文件中的内容:

I have no pride
I have no shame
You gotta make it rain
Make it rain rain rain`

我的教授希望输出看起来像这样:

{'rain': [2, 3], 'gotta': [2], 'make': [2], 'it': [2, 3], 'shame': [1], 'I': [0, 1], 'You': [2], 'have': [0, 1], 'no': [0, 1], 'Make': [3], 'pride': [0]}

例如:“雨”这个词'在第2行和第3行。 (第一行总是从零开始)

到目前为止,这是我的代码,但我需要有关此算法的帮助。

def lineIndex(fName):
    d = {}
    with open(fName, 'r') as f:       

        #algorithm goes here

print(lineIndex('index.txt'))

3 个答案:

答案 0 :(得分:1)

这是一个使用集合的简单方法,我将为您提供有关如何使用文件的练习。

In [14]: text = """I have no pride
    ...: I have no shame
    ...: You gotta make it rain
    ...: Make it rain rain rain"""

In [15]:

In [15]: from collections import defaultdict

In [16]: d = defaultdict(set)

In [17]: for i, line in enumerate(text.split('\n')):
    ...:     for each_word in line.split(' '):
    ...:         d[each_word].add(i)
    ...:
    ...:

In [18]: d
Out[18]:
defaultdict(set,
            {'I': {0, 1},
             'Make': {3},
             'You': {2},
             'gotta': {2},
             'have': {0, 1},
             'it': {2, 3},
             'make': {2},
             'no': {0, 1},
             'pride': {0},
             'rain': {2, 3},
             'shame': {1}})

答案 1 :(得分:1)

我第一次用Python写一些东西,但这很有效:

def lineIndex(fName):
    d = {}
    with open(fName, 'r') as f:       
        content = f.readlines()
        lnc = 0
        result = {}
        for line in content:
            line = line.rstrip()
            words = line.split(" ")
            for word in words:
                tmp = result.get(word)
                if tmp is None:
                    result[word] = []
                if lnc not in result[word]:
                    result[word].append(lnc)

            lnc = lnc + 1

        return result

print(lineIndex('index.txt'))

答案 2 :(得分:0)

试试这个

def lineIndex(fName):
    dic = {}
    i=0
    with open(fName, 'r') as f:       
        while True:
            x=f.readline()
            if not x:
                break
            i+=1
            for j in x:
                if j in dic:
                    dic[j].add(i)
                else:
                    dic[j]=set()
                    dic[j].add(i)
    print (dic)

print (lineIndex("index.txt"))
相关问题