python 检测含空格的一段文字是否存在于一大段文字中

在做项目的一个小分支中,需要检测“class is :0”是否存在于一行输出的内容中;如果直接用if classright in line:的话,是没有办法检测出来的,需要先使用line.replace(' ','')将空格全部去掉,然后直接用字符串匹配进行检测

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,可以使用Python的正则表达式和字典来实现。以下是示例代码: ```python import re text = """ This is a sample text. It contains some repeated sentences and phrases. This is a sample text. It contains some repeated sentences and phrases. Here is another sentence that is repeated. Here is another sentence that is repeated. Also, there are some phrases that are repeated. For example, repeated phrases. """ # Find all sentences in the text sentences = re.findall(r'[^\.\?\!]+[\.\?\!]', text) # Initialize a dictionary to store the count of each sentence sentence_count = {} # Loop through all the sentences and count their occurrences for sentence in sentences: if sentence in sentence_count: sentence_count[sentence] += 1 else: sentence_count[sentence] = 1 # Print all the sentences that occur more than once print("Repeated Sentences:") for sentence, count in sentence_count.items(): if count > 1: print(f"{sentence.strip()} ({count} times)") # Find all phrases in the text (2-5 words) phrases = re.findall(r'\b\w+(?:\s+\w+){1,4}\b', text) # Initialize a dictionary to store the count of each phrase phrase_count = {} # Loop through all the phrases and count their occurrences for phrase in phrases: if phrase in phrase_count: phrase_count[phrase] += 1 else: phrase_count[phrase] = 1 # Print all the phrases that occur more than once print("\nRepeated Phrases:") for phrase, count in phrase_count.items(): if count > 1: print(f"{phrase} ({count} times)") ``` 这个代码将输出所有重复出现的句子和词组及其出现的次数。注意,这个代码只考虑了在句子和词组之间的空格,因此可能会有一些错误匹配。如果需要更精确的匹配,可以使用更复杂的正则表达式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值