Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.8k views
in Technique[技术] by (71.8m points)

Print output in Excel file in Python

I compare two txt files, find a match and print the line that matches and three corresponding lines after. I have read How to search a text file for a specific word in Python to accomplish that.

However, I want anything printed to be exported in an excel file. I think I am getting the call out words wrong for the List.Word and Match

An example of the output I want my code to do enter image description here

import os 
import xlwt

def createlist():
    items = []
    with open('Trialrun.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

print(createlist()) 

word_list = createlist()
my_xls=xlwt.Workbook(encoding = "utf-8")
my_sheet=my_xls.add_sheet("Results")

row_num=0
my_sheet.write(row_num,0,"List.Word()")
my_sheet.write(row_num,1,"Match")
row_num+=1

with open('January 19.txt', 'r') as f:
    for line in f:
     for word in line.strip().split():
        if word in word_list:
            print'',List.Word(),',',Match (),
            print (word, end= '')
            my_sheet.write(row_num,0,List.Word())
            my_sheet.write(row_num,1,Match())
            row_num+=1
            print(next(f)) 
            print(next(f))
            print(next(f))
         
        else:
            StopIteration 
           
my_xls.save("results.xls")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't get completely what you want to achieve and, I don't understand the 2nd match and list.word occurrence as well as the print(next(f)) at the end.

But maybe something like this helps; at least the script below iterates over the file and outputs results based on a match in the 2nd file.

import os
import xlwt

def createlist():
    items = []
    with open('Trialrun.txt') as input:
        for line in input:
            items.extend(line.strip().split(','))
    return items

word_list = createlist()
my_xls = xlwt.Workbook(encoding="utf-8")
my_sheet = my_xls.add_sheet("Results")
row_num = 0
my_sheet.write(row_num, 0, "List.Word()")
my_sheet.write(row_num, 1, "Match")
row_num += 1
i = 1

with open('January 19.txt', 'r') as f:
    for line in f:
        for word in line.strip().split():
            my_sheet.write(row_num, 0, word)
            for line in word_list:
                if word in line:
                    i+=1
                    my_sheet.write(row_num, i, line)
                else:
                    StopIteration
            row_num += 1

my_xls.save("results.xls")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...