Word count after executing mysql query

18 Views Asked by At

Below is my Python code. I have no problem executing this code. But the final thing I want to accomplish is a word count of the result of the query that fetches the field, titled comment.

The query fetches the field comment and strips it from all HTML, tabs and new line breaks. The print(row) shows me the correct and desired result.

Now I want to count the words of that result. When I do: print(len(row.split())) this results in error: AttributeError: 'tuple' object has no attribute 'split'

Or this: print(len(re.findall(r'[ \n]+', row))) results in: TypeError: expected string or bytes-like object, got 'tuple'

That last example however, gives me a result of 37 when I hard code it like this (for testing)

myString = 'Alexei Navalny, who has died suddenly aged 47 while in prison, was Russia’s best-known campaigner against high-level corruption. For many years he was the leading critic and opponent of President Vladimir Putin and his political party, United Russia.'
print(len(re.findall(r'[ \n]+', myString)))

To summarize, I fetch one row and in that row is the field (the column) comment. I want a word count of the text in that specific field. How can I accomplish this? It's not important for me if the count is a couple of words off. An estimate count will be OK.

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:
                print(row)
        db.commit()
0

There are 0 best solutions below