我需要检查给定的任何两个单词,如果它们之间存在字符串或什么都不存在。
例如,我有一个句子Hey how are you?
。为此,我需要检查两个单词Hey
和how
之间是否存在任何字符串。这是我目前正在做的
s = "hey how are you?"
substring1 = 'hey'
substring2 = 'how'
my_string = s[(s.index(substring1)+len(substring1)):s.index(substring2)]
if " " in my_string:
print("no string found!")
在这里,我选择两个单词之间的任何内容,并检查它是否为空白。看来可行,但是有问题。如果我在两者之间添加一个字符串,并在其周围放置诸如"hey there how are you?"
之类的空格,它仍会显示找不到字符串。
我需要确保,如果两个词之间绝对不存在任何内容,那么只有这样,我才输出消息。我该怎么办?
答案 0 :(得分:4)
如果单词之间仅允许使用空格,则可以在空格上进行拆分,并检查from telethon import TelegramClient
# Use your own values here
api_id = 'xxx'
api_hash = 'xxx'
name = 'xxx'
channel = 'xxx'
client = TelegramClient('Lista_Membri2', api_id, api_hash)
client.start()
# get all the channels that I can access
channels = {d.entity.username: d.entity
for d in client.get_dialogs()
if d.is_channel}
# choose the one that I want list users from
channel = channels[channel]
# get all the users and print them
for u in client.iter_participants(channel, aggressive=True):
print(u.id, u.first_name, u.last_name, u.username)
#fino a qui il codice
client.disconnect()
和"hey"
的索引是否连续:
"end"
输出
s = "hey how are you?"
start = "hey"
end = "how"
words = s.split()
if abs(words.index(end) - words.index(start)) > 1:
print("something")
else:
print("nothing")
答案 1 :(得分:2)
我建议利用python内置的正则表达式库。
regex库只能在几行中提供匹配字符串的位置。
正则表达式对于模式匹配以及通过搜索特定搜索模式的一个或多个匹配项从文本中提取信息非常有用
import re
print(re.match("hey how", "hey how are you?"))
print(re.match("hey how", "hey are you ok?"))
输出
<_sre.SRE_Match object; span=(0, 7), match='hey how'>
None
答案 2 :(得分:0)
这是来自@L3viathan的评论的另一种方法。这将为使用不同的单词分隔符,标点符号等提供更多的灵活性。
test1 = 'hey how are you?'
test2 = 'ho hey and how'
match = 'hey how'
def phrase_match(s, m):
if m in s.lower():
return f'found "{m}" in "{s}"'
return f'"{m}" not found in "{s}"'
print(phrase_match(test1, match))
# found "hey how" in "hey how are you?"
print(phrase_match(test2, match))
# "hey how" not found in "ho hey and how"