【copilot+python】python 文本处理,转 csv 、markdown
·
代码
# 功能:读取"raw.md"
# 然后将每一个单词作为一列,后面的字符作为第二列
# 示例:
# 原文本:
# counterfeit 伪造的
# latent 潜在的
# interaction 相互作用
# **trivial 琐碎的,微不足道的(一般用否定形式) non-trivial意为重要的**
# bound 限制在
# 输出:
# | column1 | column2 |
# | -------- | ------- |
# | counterfeit | 伪造的 |
# | latent | 潜在的 |
# | interaction | 相互作用 |
# | trivial | 琐碎的,微不足道的(一般用否定形式) non-trivial意为重要的 |
# | bound | 限制在 |
import pandas as pd
# 建立一个 dataframe
df = pd.DataFrame(columns=['column1', 'column2'])
def run():
with open('raw.md', 'r', encoding='utf-8') as f:
lines = f.readlines()
for line in lines:
# 去掉星号
line = line.replace('*', '')
# 去掉每一行的换行符,和第一个空格
line = line.strip()
# 如果是空行,则跳过
if len(line)==0:
continue
# 如果行的第一个字符是空格,就去掉
if line[0] == ' ':
line = line[1:]
# 获取第一个英文词组,放到 column1
# 示例:"by a large scale 大规模的" -> "by a large scale"
ls = line.split(' ')
# 找到第一个中文的词语
index_zh = 0
if len(ls)==0:
continue
print(len(ls))
for i in range(len(ls)):
if(len(ls[i])==0):
continue
if ls[i][0] >= u'\u4e00' and ls[i][0] <= u'\u9fa5':
index_zh = i
break
# 中文词语前的都是 column1
column1 = ' '.join(ls[:index_zh])
# 之后的都是 column2
column2 = ' '.join(ls[index_zh:])
# 将 column1 和 column2 添加到 dataframe 中
df.loc[len(df)] = [''.join(column1), ''.join(column2)]
# 将 dataframe 保存为 csv 格式
print(df)
df.to_csv('output.csv', index=False)
# 将 dataframe 保存为 markdown 格式
# 第一行是 | column1 | column2 |,第二行是 | ----|-----|
# 后面的行是 | 单词 | 词性 |
with open('output.md', 'w', encoding='utf-8') as f:
f.write('| column1 | column2 |\n')
f.write('| ----|-----|\n')
for index, row in df.iterrows():
f.write('| ' + row['column1'] + ' | ' + row['column2'] + ' |\n')
if __name__ == '__main__':
run()
处理前文本
counterfeit 伪造的
latent 潜在的
interaction 相互作用
**trivial 琐碎的,微不足道的(一般用否定形式) non-trivial意为重要的**
bound 限制在
separate 分开的,单独的
prominent 重要的;著名的,突出的
scalar 标量
assign 确定
simultaneously 同时地
**state of the art 当前最好的(炼丹侠们的目标)**
prohibitive 禁止的
处理后文本 (markdown)
| column1 | column2 |
| ----|-----|
| counterfeit | 伪造的 |
| latent | 潜在的 |
| interaction | 相互作用 |
| trivial | 琐碎的,微不足道的(一般用否定形式) non-trivial意为重要的 |
| bound | 限制在 |
| separate | 分开的,单独的 |
| prominent | 重要的;著名的,突出的 |
更多推荐




所有评论(0)