检查多个文件中的单词,如果相同,则替换为空格

时间:2012-12-27 14:27:15

标签: python

在test01.txt

are
lol
test
hello
next

在text02.txt

lol : positive
next : objective
sunday! : objective
are : objective
you : objective
going? : neutral
mail : objective

我的代码:

file1 = open('C://Users/Desktop/test01.txt')
file2 = open('C://Users/Desktop/test02.txt')

rfile1 = file1.readlines()
rfile2 = file2.read()

for test2 in rfile2.split("\n"):
    testt2 = test2.split("\t")
    for test1 in rfile1:
        slsw1 = test1.split()
        for wttest2 in testt2:
            sttestt2 = wttest2.split(" ")
        if sttestt2[0] in slsw1[0]:
            sttestt2[0] = sttestt2[0].replace(sttestt2[0], "")
            print sttestt2[0], ":", sttestt2[2]

预期结果:

 : positive
 : objective
sunday! : objective
 : objective
you : objective
going? : neutral
mail : objective

我正在尝试用空格替换“test02.txt”中的相同单词并打印出来以查看结果但我只打印出空格。我想打印出预期结果中的所有结果。

我错过了什么吗?有什么建议吗?

2 个答案:

答案 0 :(得分:0)

# Open test02.txt in read mode
with open("C:/Users/Desktop/test02.txt", "r") as infile:
    # Read the content of the file
    content = infile.read()

# Open test01.txt in read mode
with open("C:/Users/Desktop/test01.txt", "r") as infile:
    # Loop through every line in the file
    for line in file:
        # Get the word from the line
        word = line.strip()
        # Replace "word :" with " :" from test02.txt content
        content.replace("%s :"%word, " :")

# Open test02.txt in write mode
with open("C:/Users/Desktop/test02.txt", "w") as outfile:
    # Write the new, replaced content
    outfile.write(content)

另外你应该考虑学习一些更好的命名方法。除了与文件相关的内容之外,rfile实际上并没有告诉任何内容。我宁愿使用file_contentfile_lines左右。

另外:test2, testt2, test1, slsw1, wttest2, sttestt2 ......什么?

尝试命名varibles,以便名称告诉变量的用途,对我们自己和对我们来说都会更容易。 :)

答案 1 :(得分:0)

#Create a set of all the records from the first file
lookup = set(open("test01.txt").read().splitlines())
#and then open the second file for reading and a new out file
#for writing
with open("test02.txt") as fin, open("test02.out","w") as fout:
    #iterate through each line in the file
    for line in fin:
        #and split it with the seperator
        line  = map(str.strip, line.split(":"))
        #if the key is in the lookup set 
        if line[0] in lookup:
            #replace it with space
            line[0] = " "
        #and then join the line tuple and suffix with newline
        line = ":".join(line) + "\n"
        #finally write the resultant line to the out file
        fout.write(line)