0

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」の同じ単語をスペースに置き換えて結果を表示しようとしていますが、スペースのみを印刷しました。期待される結果と同じように、すべての結果を印刷したいと思います。

私は何か見落としてますか?なにか提案を?

4

2 に答える 2

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_contentますfile_lines

また: test2, testt2, test1, slsw1, wttest2, sttestt2... なに?

変数に名前を付けて、変数が何に使用されるかを示す名前を付けてみてください。これは、あなた自身にとっても私たちにとってもはるかに簡単です。:)

于 2012-12-27T14:36:59.440 に答える
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)
于 2012-12-27T14:38:55.290 に答える