簡體   English   中英

計算Python中不同子字符串的出現

[英]Count occurrence of distinct substring in Python

我想用Python查找字符串中不同子字符串的出現。 有什么建議么?

數據集是

Fruit                     
apple|pear|grape|apple      
pear|pear|apple|apple       

我想數一數獨特的水果。 我想要的結果是:

Fruit                   Num_Fruit
------------------------------------
apple|pear|grape|apple       3
====================================
pear|pear|apple|apple        2

一去吧。

data = """
apple|pear|grape|apple
pear|pear|apple|apple
""".strip()

merged = [x.split("|") for x in data.split("\n")]

for row in merged:
  temp_val = ["|".join(row), str(len(set(row)))]
  print("|".join(temp_val))


apple|pear|grape|apple|3
pear|pear|apple|apple|2
f=open("test.txt")   #has the dataset
lines=f.readlines()

for line in lines:
    unique=[]           #store unique fruits
    line=line.rstrip()  #remove "\n"
    line=line.replace(" ",'')  #remove extra spaces
    fruits=line.split('|')  #split by delimiter 
    print(line,len(set(fruits)))

一種方法是使用設置數據結構。

暫無
暫無

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

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