如何动态搜索文件中的文本并写入另一个文件

时间:2016-02-28 02:06:11

标签: python-2.7

我会尝试尽可能具体。请记住,我上周刚刚开始学习这门语言,所以我不是专业人士。
我正在尝试制作一个能够读取我创建的词汇表文件的程序,并为此编写定义。用另一种格式的另一个预先存在的文件 这两种格式的例子以及我在这里要做的事情:
    Word 1 - 定义
    Word 1(第531页) - 其他文件的定义

我目前正在做的是我打开两个文件并根据用户输入搜索一个单词,这是行不通的。我想要做的是我希望程序进入输出文件并找到单词,然后在输入文件中找到相同的单词,仅获取定义,并将其粘贴到输出文件中。然后移动到下一个单词并循环,直到找到文件结尾。我真的不知道该怎么做,所以我现在卡住了。你如何在stackoverflow上处理这个python专业人员呢?

同样对于那些怀疑我这个项目的原因的人,我不是在试图作弊,我试图让我的大学工作提前完成,我不想与之发生冲突。我的格式与老师不同。这只是为了省时间,所以我不必两次做同样的任务。

编辑1 这是我目前从我的程序粘贴的完整代码。

import os

print("Welcome to the Key Terms Finder Program.  What class is this for?\n[A]ccess\n[V]isual Basic")
class_input = raw_input(">>")
if class_input == "A" or class_input == "a":
    class_input = "Access"
    chapter_num = 11
elif class_input == "V" or class_input == "v":
    class_input = "Visual Basic"
    chapter_num = 13
else:
    print("Incorrect Input")
print("So the class is " + class_input)
i = 1
for i in range(1, chapter_num + 1):
    try:
        os.makedirs("../Key Terms/" + class_input + "/Chapter " + str(i) + "/")
    except WindowsError:
        pass
print("What Chapter is this for? Enter just the Chapter number. Ex: 5")
chapter_input = raw_input(">>")
ChapterFolder = "../Key Terms/" + class_input + "/Chapter " + str(chapter_input) + "/"
inputFile = open(ChapterFolder + "input.txt", "r")
outputFile = open(ChapterFolder + "output.txt", "w")
line = inputFile.readlines()
i = 0
print("Let's get down to business. Enter the word you are looking to add to the file.")
print("To stop entering words, enter QWERTY")
word_input = ""
while word_input != "QWERTY":
    word_input = raw_input(">>")
    outputArea = word_input
    linelen = len(line)
    while i < linelen:
        if line[i] == word_input:
            print("Word Found")
            break
        else:
            i = i + 1
        print(i)
    i = 0

inputFile.close()
outputFile.close()

1 个答案:

答案 0 :(得分:1)

不是python pro,但是,我会尝试回答你的问题。

output=[]
word=[]
definition=[]
with open('input.txt','r') as f:
        for line in f:
                new_line=re.sub('\n','',line)
                new_line=re.sub('\s+','',line)
                word.append(new_line.split("-")[0])
                definition.append(new_line.split("-")[1])
with open('output.txt','r') as f:
        for line in f:
                new_line=re.sub('\n','',line)
                new_line=re.sub('\s+','',line)
                try:
                        index = word.index(new_line)
                        print index
                        meaning = definition[index]
                        print meaning
                        output.append(new_line+" - "+meaning)
                except ValueError as e:
                        output.append(new_line+" - meaning not found")
                        print e
f=open("output.txt","w")
f.write("\n".join(output))
f.close()

这里,input.txt是存在单词和定义的文件。 output.txt是只有单词的文件(我不清楚包含哪个output.txt只假设单词)。 上面的代码是从output.txt读取的,查看input.txt并获取定义,如果找到则跳过它。

假设是单词和定义用 -

分隔

这有帮助吗?

相关问题