zl程序教程

您现在的位置是:首页 >  后端

当前栏目

pandas读取txt---按行输入按行输出

pandas输入输出 读取 txt --- 按行
2023-06-13 09:16:07 时间

 1.pandas读取txt---按行输入按行输出

import pandas as pd
# 我们的需求是 取出所有的姓名
# test1的内容
'''
id name score
1  张三 100
2  李四 99
3  王五 98
'''
test1 = pd.read_table("test1.txt") # 这个是带有标题的文件
names = test1["name"] # 根据标题来取值
print(names)
'''
张三
李四
王五
'''

# test2的内容
'''
4  Allen 100
5  Bob 99
6  Candy 98
'''
test2 = pd.read_table("test2.txt", header=None) # 这个是没有标题的文件
names = test2[1] # 根据index来取值 
print(names)
'''
Allen
Bob
Candy
'''
import pandas as pd
from paddlenlp import Taskflow
import json

path="nlp测试体育类文本.txt"
def get_textLine(path):
    string_list = []
    file_data = pd.read_table(path,encoding="UTF-8")
    for index, elem in file_data.iterrows():
        string_list.append(elem[0])
    return string_list

# print(get_textLine(path))

data_input=get_textLine(path)


schema = ['时间', '赛手', '赛事名称']
# ie.set_schema(schema)
# ie('2月8日上午北京冬奥会自由式滑雪女子大跳台决赛中中国选手谷爱凌以188.25分获得金牌!')
# few_ie = Taskflow('information_extraction', schema=schema, task_path='./checkpoint/model_best')
few_ie = Taskflow('information_extraction', schema=schema)
# results=few_ie(['2月8日上午北京冬奥会自由式滑雪女子大跳台决赛中中国选手谷爱凌以188.25分获得金牌.',
#         '2022年8月9日上午跳高决赛中国选手李大水以100分获得金牌'])


results=few_ie(data_input)
test = pd.DataFrame(data=results)
test.to_csv('excel2txt.txt', sep='\t', index=False,header=False,index=False)
print("数据已导出")

2.with open的方式

import pandas as pd
from paddlenlp import Taskflow
import json


 def openreadtxt(file_name):
     data = []
     file = open(file_name,'r',encoding='UTF-8')  #打开文件
     file_data = file.readlines() #读取所有行
     for row in file_data:
         data.append(row) #将每行数据插入data中     
     return data
data_input=openreadtxt("nlp测试体育类文本.txt")

schema = ['时间', '赛手', '赛事名称']
# ie.set_schema(schema)
# ie('2月8日上午北京冬奥会自由式滑雪女子大跳台决赛中中国选手谷爱凌以188.25分获得金牌!')
# few_ie = Taskflow('information_extraction', schema=schema, task_path='./checkpoint/model_best')
few_ie = Taskflow('information_extraction', schema=schema)



results=few_ie(data_input)
 with open("test.txt", "w+") as f:    #a :   写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾
     for result in results:
         line = json.dumps(result, ensure_ascii=False)  #对中文默认使用的ascii编码.想输出真正的中文需要指定ensure_ascii=False
         f.write(line + "\n")


print("数据已导出")