python - Python - 将文本解析、拆分和分离成单独的行
问题描述
我有一个文本文件,其中包含要导入 Access 数据库的数据。文本文件包含几段我想进入一行。我已经用“@@@”分隔了我想要的每一行
所以这是我所拥有的一个例子:
@@@我想去上学,因为它很有趣。呜呜呜呜呜呜。我今天玩得很开心。@@@我无缘无故的高兴。呸呸呸呸呸。我今天玩得很开心。
我希望它看起来像这样:
身份证 | 报告文本
1 | 我想去上学,因为它很有趣。呜呜呜呜呜呜。我今天玩得很开心。
2 | 我无缘无故地高兴。呸呸呸呸呸。我今天玩得很开心。
但是,我知道我的代码很接近,但我得到了这个:
身份证 | 报告文本
1 | 我想去上学,因为它很有趣。呜呜呜呜呜呜。
2 | 我今天玩得很开心。
3 | 我无缘无故地高兴。呸呸呸呸呸。我有这么多
4 | 我今天玩得很开心。
我尝试了一个 IF 语句,只在行中有“@@@”时添加 ID,但我无法让它工作。如果我这样做了,我认为它应该可以工作。我有 ID 和 reporttext 使用分号作为分隔符。
这是我的代码:
import csv
with open("by2.txt") as txt, open('theoutput2.txt', 'a') as csvfile:
writer = csv.writer(csvfile, delimiter=';')
writer.writerow(('ID', 'Reporttext'))
Id = 1
for line in txt:
words = line.strip().split("@@@")
for word in words:
writer.writerow((id, word.strip()))
id += 1
解决方案
您可以组合split("@@@")
并enumerate(iterable,start_index)
结合生成器表达式:
t = """@@@ I would like to go to school because it's so much fun. Blah Blah Blah Blah. I am having so much fun today. @@@ I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much fun today."""
# split and enumerate(starting at 1)
# the if conditional inside the generator expression eleminates empty lines
data = list(enumerate( (x.strip() for x in t.split("@@@") if x.strip()), 1))
print(data)
print("")
import csv
with open("t.txt", "w", newline = "") as csvfile:
writer = csv.writer(csvfile, delimiter=';')
writer.writerow(('ID', 'Reporttext'))
writer.writerows(data)
print( open("t.txt").read())
输出:
# data
[(1, "I would like to go to school because it's so much fun. Blah Blah Blah Blah. I am having so much fun today."),
(2, 'I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much fun today.')]
# file
ID;Reporttext
1;I would like to go to school because it's so much fun. Blah Blah Blah Blah. I am having so much fun today.
2;I am so happy for no reason. Blah Blah Blah Blah Blah. I am having so much fun today.
独库:
推荐阅读
- javascript - 将加载的组件显示为绝对悬念反应的背景?
- c# - 迁移到 PackageReference 后构建失败
- google-chrome - 谷歌浏览器中这些 http-livestream 伪影的原因可能是什么?
- reactjs - React Bootstrap 导航样式更改
- curl - curl请求下载文件的身份验证错误
- puppeteer-sharp - PuppeteerSharp 3.0.0 版 - 无法在运行时加载程序集
- android - 是否需要启用位置权限和位置服务才能通过 MAC ID 连接到 BLE 设备
- sml - SML:带常量的模式?
- webpack - 在 Rails 6 Webpack 应用程序中导入时 CKEditor 未定义
- visual-studio-code - VSCode 不会向语言服务器发出 DidRenameFiles 通知