简体   繁体   English

只有一个单词正在从.txt 文件中读取

[英]Only one word is reading from .txt file

I am building a BlogApp and I am implementing a Feature,我正在构建一个 BlogApp 并且我正在实现一个功能,

What i am trying to do:-我正在尝试做的事情:-

I am trying to read and work on .txt file BUT when i write one word then it works fine BUT when i write two words then it is not working.我正在尝试阅读和处理.txt文件,但是当我写一个单词时它可以正常工作,但是当我写两个单词时它不起作用。

views.py视图.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)

wordlists.txt单词表.txt

good
bad

When i add good word ( only one word ) then it works fine BUT when i add bad after good then both doesn't work.当我添加good词(只有一个词)时,它可以正常工作,但是当我在好之后添加bad词时,两者都不起作用。

I have no idea, where is the mistake.我不知道,错在哪里。 Any help would be Appreciated.任何帮助,将不胜感激。 Thank You in Advance.先感谢您。

I used operator._or instead of operator.and__ AND IT WORKED CORRECTLY.我使用了operator._or而不是operator.and__并且它工作正常。

Where operator.or_ ?在哪里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----------------------------------------------^

You should use operator._or as reducer, not operator._and , since you want to exclude that contain the word good, or the word bad, et.您应该使用operator._or作为减速器,而不是operator._and ,因为您要排除包含单词 good 或 bad 等的单词。

You do not need to work with reduce , since Django has defined some arithmetic for Q objects.您不需要使用reduce ,因为 Django 已经为Q对象定义了一些算法。 You can define this as:您可以将其定义为:

posts = Post.objects.exclude(
    Q(
        *[Q(description__contains=x) for x in wordlist],
        _connector=Q.OR
    )
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM