检查多个文件中的字,如果相同,则用sp替换

2024-07-03 07:26:20 发布

您现在位置: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”中的同一个单词,并打印出来查看结果,但我只得到了打印出来的空格。我想按预期结果打印所有结果。你知道吗

我错过什么了吗?有什么建议吗?你知道吗


Tags: intxtyouforarenexttest01split
2条回答
#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)
# 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。。。什么?你知道吗

试着命名你的变量,这样名字就可以告诉你变量的用途,这对你自己和我们来说都会容易得多。:)

相关问题 更多 >