Python中字符串查找的逻辑

3 投票
5 回答
968 浏览
提问于 2025-04-16 12:36
filtered=[]
text="any.pdf"
if "doc" and "pdf" and "xls" and "jpg" not in text:
    filtered.append(text)
print(filtered)

这是我在Stack Overflow上的第一篇帖子,如果问题中有什么让人烦恼的地方,请多多包涵。我的代码是用来添加文本的,前提是这个文本里不包含以下这些词:doc、pdf、xls、jpg。如果文本是这样的,它的运行效果很好:

if "doc" in text:
elif "jpg" in text:
elif "pdf" in text:
elif "xls" in text:
else:
    filtered.append(text)

5 个回答

3

在编程中,有时候我们会遇到一些问题,比如代码运行不正常或者出现错误。这些问题可能是因为我们没有正确理解某些概念或者没有按照正确的方式使用代码。

当你在编写代码时,确保你理解每一行代码的作用。不要害怕去查阅资料或者请教别人,尤其是当你遇到困难的时候。编程就像学习一门新语言,刚开始可能会觉得很难,但只要坚持练习,就会慢慢变得熟练。

另外,记得多做实验。尝试修改代码,看看会发生什么变化。这种实践能帮助你更好地理解代码的运行方式。

总之,编程需要耐心和不断的学习,不要因为遇到问题就气馁。每个人都是从零开始的,慢慢来,你会越来越好的。

basename, ext = os.path.splitext(some_filename)
if not ext in ('.pdf', '.png'):
   filtered.append(some_filename)
....
4

如果这些扩展名总是出现在字符串的末尾,你可以使用.endswith这个方法,它可以处理多个扩展名。

if not text.endswith(("doc", "pdf", "xls", "jpg")):
    filtered.append(text)
6

如果你打开一个Python解释器,你会发现 "doc" 和 "pdf" 和 "xls" 和 "jpg"'jpg' 是一样的意思:

>>> "doc" and "pdf" and "xls" and "jpg"
'jpg'

所以,与其去检查所有的字符串,你可以先只检查 'jpg'。

有很多方法可以实现你想要的效果。下面的方法虽然不是最明显的,但还是挺有用的:

if not any(test_string in text for test_string in ["doc", "pdf", "xls", "jpg"]):
    filtered.append(text)

另一种方法是结合使用 for 循环和 else 语句:

for test_string in ["doc", "pdf", "xls", "jpg"]:
    if test_string in text:
        break
else: 
    filtered.append(text)

最后,你还可以使用纯粹的列表推导式:

tofilter = ["one.pdf", "two.txt", "three.jpg", "four.png"]
test_strings = ["doc", "pdf", "xls", "jpg"]
filtered = [s for s in tofilter if not any(t in s for t in test_strings)]

编辑:

如果你想同时过滤单词和扩展名,我推荐以下方法:

text_list = generate_text_list() # or whatever you do to get a text sequence
extensions = ['.doc', '.pdf', '.xls', '.jpg']
words = ['some', 'words', 'to', 'filter']
text_list = [text for text in text_list if not text.endswith(tuple(extensions))]
text_list = [text for text in text_list if not any(word in text for word in words)]

这可能仍然会导致一些不匹配;上面的代码也会过滤掉 "做某事"、"他是个文字大师" 等等。如果这造成了问题,你可能需要一个更复杂的解决方案。

撰写回答