[英]Only one word is reading from .txt file
我正在构建一个 BlogApp 并且我正在实现一个功能,
我正在尝试做的事情:-
我正在尝试阅读和处理.txt
文件,但是当我写一个单词时它可以正常工作,但是当我写两个单词时它不起作用。
视图.py
def defining(request):
with open('wordlists.txt') as in_file:
wordlist = in_file.read().splitlines()
posts = Post.exclude.exclude(reduce(operator.and_,(Q(description__contains=x) for x in wordlist)))
context = {'posts':posts}
return render(request, 'defining.html', context)
单词表.txt
good
bad
当我添加good
词(只有一个词)时,它可以正常工作,但是当我在好之后添加bad
词时,两者都不起作用。
我不知道,错在哪里。 任何帮助,将不胜感激。 先感谢您。
我使用了operator._or而不是operator.and__
并且它工作正常。
在哪里operator.or_
?
from django.db.models import Q
from functools import reduce
def defining(request):
with open('wordlists.txt') as in_file:
wordlist = in_file.read().split()
posts = Post.objects.exclude(reduce(operator.or_,(Q(description__contains=x) for x in wordlist)))
HERE----------------------------------------------^
您应该使用operator._or
作为减速器,而不是operator._and
,因为您要排除包含单词 good 或 bad 等的单词。
您不需要使用reduce
,因为 Django 已经为Q
对象定义了一些算法。 您可以将其定义为:
posts = Post.objects.exclude(
Q(
*[Q(description__contains=x) for x in wordlist],
_connector=Q.OR
)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.