记录DEMO
txt数据
非常 漂亮 的 拉杆箱 , 很 轻 , 跟 店家 描述 的 一致 , 快递 速度 不行 啊
快递
0
款式 设计 的 很 好看 呀 , 客服 态度 很好 , 呃 , 质量 感觉 不太好 奥 , 就是 会 起球 , 而且 快递 好慢 啊
质量
0
超值 啊 哈哈哈 , 就是 颜色 随机 我以 为什么 颜色 都 有 , 结果 全是 一个 颜色 的 , 不过 东西 好 就 可以 , 物超所值 。
颜色
0
卖家 很好 , 热情周到 , 包装 严实 , 遇到 快递 问题 都 极力 解决 。 我要 投诉 快递 , 太差 了 。
快递
0
需求
将txt文本中的三行数据合并成一行数据,分别对应 评论 + 原因 + 等级
Java代码
描述:建立的是maven项目,导入处理excel的相关坐标
<!--处理excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author wangxin
* @create 2021/11/13 - 14:26
*/
public class demo {
public static void main(String[] args) {
File file = new File("demo.txt");
readTxtToExcel(file);
}
public static void readTxtToExcel(File file) {
BufferedReader reader = null;
try {
//读文件
List<String[]> data = new ArrayList<>();
reader = new BufferedReader(new FileReader(file));
String str = null;
//行号
int line = 0;
//1、创建Workbook
Workbook workbook = new HSSFWorkbook();
//2、创建sheet,默认名字是sheet1,sheet2...
Sheet sheet = workbook.createSheet();
//3、创建row 参数是0代表第1行,参数是1代表第二行...
while ((str = reader.readLine()) != null) {
Row row1 = sheet.createRow(line);
String[] strs = new String[3];
//评论+原因+等级
strs[0] = str;
strs[1] = reader.readLine();
strs[2] = reader.readLine();
//写入excel
for (int j = 0; j < strs.length; j++) {
//4、创建cell 第0列
//5、在cell中填充数据
row1.createCell(j).setCellValue(strs[j]);
}
line ++ ;
data.add(strs);
}
for (String[] datum : data) {
System.out.println(datum[0]);
}
//6、向文件中写入数据,以上步骤都是在内存中完成的,想要将文件持久化到磁盘需要文件输出流
FileOutputStream outputStream = new FileOutputStream("demo.xls");
workbook.write(outputStream);
//7、关闭流
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Python
import xlwt
# 读txt
file = r"train.txt"
excel = xlwt.Workbook()
sheet1 = excel.add_sheet(u'sheet1', cell_overwrite_ok=True) # 创建sheet
with open(file, encoding="utf-8") as f: # 打开文件
lines = f.readlines()
# 三行为一条记录
for i in range(int(len(lines) / 3)):
# 读取第一行为内容
word = lines[i * 3].strip()
# 读取第二行为原因
case = lines[i * 3 + 1].strip()
# 读取第三行为标签
label = lines[i * 3 + 2].strip()
# 将数据写入第 i 行,第 j 列
sheet1.write(i, 0, word)
sheet1.write(i, 1, case)
sheet1.write(i, 2, label)
excel.save("train.xlsx") # 保存文件
结果
还是python简洁。科研利器