如何从一个文本文件中取出另一个文本?蟒蛇

时间:2016-04-19 21:27:17

标签: python file

tran = open("rep-small.txt")
stop = open("stopSQL.txt")
cTran = open("cleanTran.txt.","w")

badList = []
for line in stop:
    badList.append(line)

def cleantxt():
    for line in tran:
        for word in badList:
            line = line.replace(word,"")
        cTran.write(line)

正在编写cTran.txt,但它没有从停止中取出单词。 停止文件的格式如下:

将每个单词放在不同的行上。

2 个答案:

答案 0 :(得分:0)

你可以跳过for循环: (顺便问一下你在调用函数cleantxt()吗?)

tran = open("rep-small.txt")

cTran = open("cleanTran.txt.","w")

def cleantxt():
    for line in tran.readlines():
        for word in badList:
            line = line.replace(word,"")
        cTran.write(line)
    ctran.close()

with open("stopSQL.txt") as stop: # The With-Statement calls the close() function after its finished executing
    badList = stop.readlines() # Add lines to list

cleantxt()

答案 1 :(得分:-1)

你从来没有读过“停止”作为行,试试

for line in stop.readlines():