首页 > 解决方案 > 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.

enter image description here

I expect output to be:

Supplychain
Workshop
Customer

标签: pythontext

解决方案


我的做法:

# 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)

推荐阅读