Learning Python 016 写文件时,将其用指定的编码方式保存(比如:UTF-8无BOM编码方式)


  • 使用的电脑系统:Windows 10 64位
  • 使用的开发集成环境:PyCharm 2016.1.4
  • 使用的Python的版本:python 3.5.0

学习这个知识点的原因

举一个实例:

Octopress站点路径里面博文文件(.markdown后缀文件)必须要是以UTF-8无BOM编码方式编码的文件,否则执行rake generate命令会出现下面这个错误:

Alt text

Error reading file F:/octopress/source/_posts/xxxx.markdown: invalid byte sequence in UTF-8
  Liquid Exception: invalid byte sequence in UTF-8 in _posts/xxxx.markdown/#excerpt

所以,为了解决不要出现这个问题,我们需要将文件指定你希望的编码方式保存。

将其用指定的编码方式保存(比如:UTF-8无BOM编码方式)

其实很简单,我们只需要这样做:

file = open(file_path, 'w', encoding='utf-8')

这样file文件就是以Utf-8无BOM编码方式编码的文件。

我们也看到了,其实不是将file保存为以Utf-8无BOM编码方式编码的文件,而是创建这个一个以Utf-8无BOM编码方式编码的文件 file

import pandas as pd import re def process_wos_file(input_path, output_path): """ 处理Web of Science导出的TXT文件 :param input_path: 输入TXT文件路径 :param output_path: 输出Excel文件路径 """ # 初始化存储列表 records = [] current_record = {"AB": "", "KW": ""} # 正则表达式匹配字段标签 field_pattern = re.compile(r'^([A-Z]{2})\s(.*)') with open(input_path, 'r', encoding='utf-8') as f: for line in f: line = line.strip() # 检测新记录开始 (PT = 出版物类型) if line.startswith("PT "): if current_record["AB"] or current_record["KW"]: records.append(current_record) current_record = {"AB": "", "KW": ""} continue # 匹配字段标签 match = field_pattern.match(line) if match: field_type, content = match.groups() if field_type == "AB": current_record["AB"] = content elif field_type == "KW": current_record["KW"] = content continue # 处理多行文本(续行) if current_record["AB"] and not line.startswith((" ", "\t")) and not field_pattern.match(line): current_record["AB"] += " " + line if current_record["KW"] and not line.startswith((" ", "\t")) and not field_pattern.match(line): current_record["KW"] += " " + line # 添加最后一条记录 if current_record["AB"] or current_record["KW"]: records.append(current_record) # 创建DataFrame并保存Excel df = pd.DataFrame(records) df.to_excel(output_path, index=False) print(f"成功处理 {len(df)} 条记录,已保存到 {output_path}") # 使用示例 if __name__ == "__main__": input_file = r"C:\Users\17844\Desktop\PCOS bibilometric\VOSviewer\34 1页.txt" # 替换为你的输入文件路径 output_file = w"C:\Users\17844\Desktop\PCOS bibilometric\LDA预处理英文数据\processed_data.xlsx" # 替换为你的输出文件路径 process_wos_file(input_file, output_file) 上述代码生成了xsxl表格但0条处理记录,为什么
最新发布
10-04
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值