Python 迭代文件并从其他文件获取单词索引

Python 迭代文件并从其他文件获取单词索引,python,python-2.7,Python,Python 2.7,我需要迭代两个文件中的所有行(有点同时),并从其中一个文件的一个单词中获取索引 例如: 小字表: Book Woman Child Book Man Dog Cat Child Dinosaur Woman 大字表: Book Woman Child Book Man Dog Cat Child Dinosaur Woman 等等。 希望的结果是: 1 7 5 (或者从0开始,每次少一个,这并不重要)并将其保存到另一个文件中 我无法让它与这样的东西一起工作: g = open('big

我需要迭代两个文件中的所有行(有点同时),并从其中一个文件的一个单词中获取索引

例如:

小字表:

Book
Woman
Child
Book
Man
Dog
Cat
Child
Dinosaur
Woman
大字表:

Book
Woman
Child
Book
Man
Dog
Cat
Child
Dinosaur
Woman
等等。 希望的结果是:

1
7
5
(或者从0开始,每次少一个,这并不重要)并将其保存到另一个文件中

我无法让它与这样的东西一起工作:

g = open('big_wordlist', 'r')
i = open('index_list', 'w')

with open('small_wordlist', 'r') as h:
for line in h:
    p = h.readline()
    for num, line in enumerate(g):          # num is my found index
            if (line.startswith(p + "\n")): # need that to make sure we only get the correct word and nothing before / after it
                 i.write("%s" % (num) + "\n")
因此,我需要迭代小单词列表,从大词列表中找到的单词中获取特定的单词索引,并将其写入我的索引列表中

现在我得到了“混合迭代和读取方法将丢失数据”-我不关心在我将num写入索引列表后,p(当时的单词)将随着小单词列表中的每一行而改变(并且应该改变)


我在小字表上迭代时遇到了问题,当我用“Book”替换p时,它确实可以工作,现在我需要使用一个变量,即小字表每行中的单词。

您不需要同时处理这两个文件。相反,您需要为第一个文件建立索引,然后处理第二个文件,在索引中查找单词

#!python3

small_wordlist = """
    Book
    Woman
    Child
""".strip()

big_wordlist = """
    Book
    Man
    Dog
    Cat
    Child
    Dinosaur
    Woman
""".strip()

import io

# Read the words from the big wordlist into word_index

#with open('big_wordlist.txt') as big:
with io.StringIO(big_wordlist) as big:
    ix = 0
    word_index = {}

    for line in big:
        word = line.strip()
        if word not in word_index:
            word_index[word] = ix
        ix += 1

#with open('small_wordlist.txt') as small:
with io.StringIO(small_wordlist) as small:
    for line in small:
        word = line.strip()
        if word not in word_index:
            print('-1')  # Or print('not found') or raise exception or...
        else:
            print(word_index[word])

你能把它加载到内存中吗?是的,我可以,但如果我不这样做会更好,现在我想我会很高兴的。谢谢,它工作得很好,好像我走错了路!