簡體   English   中英

僅返回句子中的第一個單詞和文本文件中的所有其他唯一單詞?

[英]Return only the first word from a sentence and all other unique words from text file?

假設我有一個文本文件“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.

我怎樣才能只返回第一個單詞而不重復,它們應該是唯一的?

我嘗試過這樣解決,也嘗試過其他方法,但我只得到了重復和整個路徑的完整列表。

在此處輸入圖像描述

我希望 output 是:

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)

你可以做:

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)

這樣做的一種方法是:

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

這將為您提供沒有重復的第一個單詞的列表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM