对停用词进行标记,生成的标记 ['ha', 'le', 'u', 'wa'] 不在 stop_words 中

2024-03-12

我正在使用 Python 制作一个聊天机器人。 代码:

import nltk
import numpy as np
import random
import string 
f=open('/home/hostbooks/ML/stewy/speech/chatbot.txt','r',errors = 'ignore')
raw=f.read()
raw=raw.lower()# converts to lowercase

sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences 
word_tokens = nltk.word_tokenize(raw)# converts to list of words

lemmer = nltk.stem.WordNetLemmatizer()    

def LemTokens(tokens):
    return [lemmer.lemmatize(token) for token in tokens]

remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

def LemNormalize(text):
    return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))

GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey","hii")
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are talking to me"]


def greeting(sentence):
    for word in sentence.split():
        if word.lower() in GREETING_INPUTS:
            return random.choice(GREETING_RESPONSES)

from sklearn.feature_extraction.text import TfidfVectorizer

from sklearn.metrics.pairwise import cosine_similarity

def response(user_response):
    robo_response=''
    sent_tokens.append(user_response)    

    TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
    tfidf = TfidfVec.fit_transform(sent_tokens)
    vals = cosine_similarity(tfidf[-1], tfidf)
    idx=vals.argsort()[0][-2]
    flat = vals.flatten()
    flat.sort()
    req_tfidf = flat[-2]    

    if(req_tfidf==0):
        robo_response=robo_response+"I am sorry! I don't understand you"
        return robo_response
    else:
        robo_response = robo_response+sent_tokens[idx]
        return robo_response

flag=True
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit, type Bye!")

while(flag==True):
    user_response = input()
    user_response=user_response.lower()
    if(user_response!='bye'):
        if(user_response=='thanks' or user_response=='thank you' ):
            flag=False
            print("ROBO: You are welcome..")
        else:
            if(greeting(user_response)!=None):
                print("ROBO: "+greeting(user_response))
            else:
                print("ROBO: ",end="")
                print(response(user_response))
                sent_tokens.remove(user_response)
    else:
        flag=False
        print("ROBO: Bye! take care..")

它运行良好,但每次对话都会出现此错误:

/home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. 

Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words.

以下是 CMD 的一些对话:

ROBO:聊天机器人是一种通过听觉或文本方法进行对话的软件。

印度是什么

    /home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. 'stop_words.' % sorted(inconsistent))

ROBO:印度的野生动物传统上在印度文化中被视为宽容,它们在这些森林和其他受保护的栖息地中得到了支持。

什么是聊天机器人

    /home/hostbooks/django1/myproject/lib/python3.6/site-packages/sklearn/feature_extraction/text.py:300: UserWarning: Your stop_words may be inconsistent with your preprocessing. Tokenizing the stop words generated tokens ['ha', 'le', 'u', 'wa'] not in stop_words. 'stop_words.' % sorted(inconsistent))

ROBO:聊天机器人是一种通过听觉或文本方法进行对话的软件。


原因是你使用了自定义的tokenizer并使用默认值stop_words='english'因此,在提取特征时,会检查特征之间是否存在不一致stop_words and tokenizer

如果你更深入地研究代码sklearn/feature_extraction/text.py您会发现此代码片段执行一致性检查:

def _check_stop_words_consistency(self, stop_words, preprocess, tokenize):
    """Check if stop words are consistent

    Returns
    -------
    is_consistent : True if stop words are consistent with the preprocessor
                    and tokenizer, False if they are not, None if the check
                    was previously performed, "error" if it could not be
                    performed (e.g. because of the use of a custom
                    preprocessor / tokenizer)
    """
    if id(self.stop_words) == getattr(self, '_stop_words_id', None):
        # Stop words are were previously validated
        return None

    # NB: stop_words is validated, unlike self.stop_words
    try:
        inconsistent = set()
        for w in stop_words or ():
            tokens = list(tokenize(preprocess(w)))
            for token in tokens:
                if token not in stop_words:
                    inconsistent.add(token)
        self._stop_words_id = id(self.stop_words)

        if inconsistent:
            warnings.warn('Your stop_words may be inconsistent with '
                          'your preprocessing. Tokenizing the stop '
                          'words generated tokens %r not in '
                          'stop_words.' % sorted(inconsistent))

正如您所看到的,如果发现不一致,它会发出警告。

希望能帮助到你。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

对停用词进行标记,生成的标记 ['ha', 'le', 'u', 'wa'] 不在 stop_words 中 的相关文章

随机推荐

  • 不相关实体的 HQL 左连接

    我有 2 个实体 A and B 它们是相关的 但我不想将关系映射添加到 bean 我们如何使用之间的左外连接A and B使用 HQL 或标准 有一些解决方法可以解决这个问题 按照指示使用本机 SQLhere https stackove
  • 大型 WCF Web 服务请求因 (400) HTTP 错误请求而失败

    我遇到过这个明显常见的问题 但无法解决 如果我使用数组参数中相对较少的项目 我已测试最多 50 个 来调用 WCF Web 服务 则一切都很好 但是 如果我调用包含 500 个项目的 Web 服务 则会收到错误请求错误 有趣的是 我跑过Wi
  • 从 Bash 函数返回字典

    我想在 bash 中有一个函数 它创建一个字典作为局部变量 用一个元素填充字典 然后返回该字典作为输出 下面的代码正确吗 function Dictionary Builder local The Dictionary unset The
  • python 的 random.Random.seed 是如何工作的?

    我习惯打字random randrange 我会做一个from random import Random从现在开始发现错误 对于涉及程序生成的游戏 不 不是 Minecraft 克隆 p 我想保留几个不同的伪随机数生成器 一个用于世界的生成
  • 使用传单和 R 向 CircleMarkers 添加边框

    我想为 CircleMarkers 添加边框 我使用了以下代码 我找不到任何为笔画添加黑色边框的功能 pal lt colorNumeric palette RdYlBu domain city results ratio m lt lea
  • 合并一个数组中的两个 int 数组,且不重复

    我正在尝试将两个数组合并为一个而不重复 但我的代码无法正常工作 谁能建议如何解决这个问题 void unify int set A int size A int set B int size B int set C int size C i
  • Flurry Android Analytics 中未获取报告

    我已将 Flurry Analytics 集成到我的应用程序中 但无法获取 Flurry Dashboard 上的报告 但我按照 Flurry ReadMe PDF 中提到的方式集成了它 我使用 API 密钥实现了所需的所有代码 但不知道为
  • Rails Devise:登录后如何访问注册页面?

    我是 Rails 新手 我正在使用 devise gem 进行身份验证 首先 我通过默认注册页面添加一个新用户 例如 users sign up 然后 我按照以下说明将 sign up 页面设置为仅对符号用户可用 在过滤器之前设计阻止访问
  • 从我的 git 历史记录中删除 4 个提交

    我已经完成了一些提交并将它们推送到我的存储库中 然后我做了一个拉取请求 但我意识到有一些提交我不想出现在拉取请求中 它们看起来像这样 My commits look like this Correct HTML ab1c41c HTML e
  • 使用 WiX 创建语言选择对话框

    我使用 WiX 创建了一个多语言安装程序 我正在使用命令从命令行运行安装程序 msiexec i myinstaller msi TRANSFORMS 1041 并且工作正常 现在我已经使用引导程序创建了一个语言选择对话框 如何将所选语言传
  • 如何将Win32 HRESULT转换为int返回值?

    我正在用 C 编写一个 Windows 控制台应用程序 希望在成功时返回零 在失败时返回有意义的错误代码 即 S OK应该返回 0 并且E OUTOFMEMORY应该返回不同的返回值E FAIL等等 以下是一个好的方法吗 int wmain
  • 对于 std::string,复制初始化或直接初始化字符串文字更快吗?

    我有以下问题 应该遵循哪一项更好 为什么 string strMyString SampleString or string strMyString SampleString 我回答了here https stackoverflow com
  • Chrome 中的 Math.log2 精度已更改

    我编写了一个 JavaScript 程序 它根据元素的数量计算二叉树的深度 我的程序几个月来一直运行良好 但最近我发现在 Chrome 和 Firefox 中查看网页时存在差异 特别是在 Firefox 上 Math log2 8 3 但现
  • 高效处理超宽但不太高的位图?

    有什么方法可以创建更节省空间 资源的位图吗 目前我尝试渲染一个文件 高约 800px 宽约 720000px 它使我的应用程序崩溃 大概是因为位图的共享内存大小 我是否可以更有效地执行此操作 例如直接将其创建为 gif 而不是稍后保存 我尝
  • Elif,如果不工作或者我不理解[重复]

    这个问题在这里已经有答案了 好吧 我的代码可以正常工作 但是当我输入 否 时 如果我想重试输入密码 它就不起作用了 它只是转到输入密码行 第 20 行 我尝试了多种方法来解决这个问题 但我就是做不到 import time import o
  • 未捕获的类型错误:$(…).on 不是函数

    我在页面上使用 JQuery UI 对话框并收到此错误
  • 如何更好地拟合seaborn小提琴图

    下面的代码给了我一个非常漂亮的小提琴图 以及其中的箱线图 import numpy as np import seaborn as sns import matplotlib pyplot as plt foo np random rand
  • 错误:类...没有名为的字段或关联

    当我将文件上传到服务器时遇到这个问题 Error Class Prizes PrizesBundle Entity Category has no field or association named order cat 我的类别
  • C#:如何以编程方式将 SQL 脚本导入数据库?

    我是否必须手动解析 SQL 脚本并单独执行每个语句 还是有更好的方法 我正在寻找一种编程解决方案 我知道有些工具已经能够做到这一点 如果该解决方案适用于所有数据库系统 而不仅仅是 sqlite 那就太好了 我不确定这如何适用于 Sqlite
  • 对停用词进行标记,生成的标记 ['ha', 'le', 'u', 'wa'] 不在 stop_words 中

    我正在使用 Python 制作一个聊天机器人 代码 import nltk import numpy as np import random import string f open home hostbooks ML stewy spee