只返回句子中的第一个单词和文本文件中的所有其他唯一单词



假设我有一个文本文件"list.txt">,它看起来像这样:

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.

我怎样才能只返回第一个单词而不重复,它们应该是唯一的?

我试过这样解决问题,也尝试过其他方法,但我只得到了完整的重复列表和整个路径。

在此处输入图像描述

我预计输出为:

Supplychain
Workshop
Customer

一种单行方法是:

textfile = open("list.txt")
words = set(i.strip().split('/')[0] for i in textfile.readlines())

这将给你一个没有重复的第一个单词的列表。

我的方法:

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

你可以做:

result = []
with open("RestRout3.txt", "r") as f:
for line in f.readlines():
# Traiter la ligne et ainsi de suite ...
first_word = line.split('/')[0]
print(first_word)
if not(first_word in result):
result.append(first_word)
print(result)

相关内容

最新更新