python - Return only the first word from a sentence and all other unique words from text file?
问题描述
Say I have a text file "list.txt" which looks like this:
Supplychain/dealer/etc.
Supplychain/parts/etc.
Supplychain/shop/etc.
Supplychain/order/etc.
Supplychain/tasks/etc.
Supplychain/payment/etc.
Workshop/location/etc.
Workshop/name/etc.
Workshop/report/etc.
Customer/info/etc.
Customer/order/etc.
How can I get return only the first word without duplication, they shall be unique?
I have tried to solve like this and have tried other methods too, but I only get the full list of duplication and whole path.
I expect output to be:
Supplychain
Workshop
Customer
解决方案
我的做法:
# Step 1 - extract the first words
file_content = """Supplychain/dealer/etc.
Supplychain/parts/etc.
Supplychain/shop/etc.
Supplychain/order/etc.
Supplychain/tasks/etc.
Supplychain/payment/etc.
Workshop/location/etc.
Workshop/name/etc.
Workshop/report/etc.
Customer/info/etc.
Customer/order/etc."""
words = file_content.split('\n') # Splitting by new line
first_parts = [word.split('/')[0] for word in words] # Get the part of the string that is before the '/'
# Step 2 - Get the unique parts
unique_first_parts = set(first_parts)
推荐阅读
- apollo - apollo 服务器从 apollo 上传客户端接收空对象
- angular - 修改一个查询参数:express JS get请求
- php - 如何修复“require_once() 无法打开流”
- ansible - Ansible - 无法通过 ssh 连接到主机:权限被拒绝(公钥,...密码)
- dart - 多次打开页面错误
- ios - 在 App Messaging 的 Firebase 中添加两个按钮
- javascript - 将圆圈添加到svg时如何最小化回流
- react-native - 在反应原生中保存平面列表项目的项目 Onpress
- python - 有没有办法将其转换为训练卷积自动编码器?
- css - 为什么我的图像隐藏了 h2?为什么导航不是水平渲染的?