You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行MySQL查询后对comment字段结果进行词频统计报错求助

解决MySQL查询结果统计词数时的元组类型错误问题

你的问题核心是查询返回的row是元组而非字符串:mycursor.fetchall()返回的是元组列表,哪怕只查询一条数据,每个row都是包含单个字段值的元组,直接对元组调用字符串方法或传入正则函数自然会报错。

修改方案

方案1:处理fetchall返回的结果

直接提取元组中的第一个元素(因为你的SELECT只返回了一个字段),再进行词数统计:

import re
import requests
import mysql.connector

db = mysql.connector.connect(
host='myHost',
user=('myUsername'),
passwd=('myPassword'),
database=('myDB')
)

mycursor = db.cursor()

try: 
       mycursor.execute("SELECT REPLACE(REPLACE(REGEXP_REPLACE(`comment`, '(<[^>]*>)|(&nbsp;)', ''), '\t', ''), '\n', '') AS Replaced_Comment FROM data WHERE id = 1") 
except: 
        print('Sorry ! There was an error ')  
finally:  
        results = mycursor.fetchall()
        for row in results:
                # 取出元组中的评论文本字符串
                comment_text = row[0]
                print(comment_text)
                # 按空白符分割统计词数(允许少量误差)
                word_count = len(comment_text.split())
                print(f"词数:{word_count}")
        db.commit()

方案2:用fetchone简化单条数据查询

因为你只查询一条数据,用fetchone()直接获取单个元组,无需循环,更高效:

# ... 前面连接数据库和执行语句的代码不变
finally:  
        result = mycursor.fetchone()
        if result:
                comment_text = result[0]
                print(comment_text)
                word_count = len(comment_text.split())
                print(f"词数:{word_count}")
        db.commit()

词数统计补充说明

  • split()默认按任意空白符(空格、制表符、换行等)分割,统计结果符合你“允许少量误差”的需求。
  • 如果需要更精准的单词匹配(比如排除纯符号),可以用正则:
    word_count = len(re.findall(r'\w+', comment_text))
    

内容的提问来源于stack exchange,提问作者Bart Zakkenwasser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 22:23:16