Меню

Attributeerror nonetype object has no attribute group ошибка

Can somebody help me with this code? I’m trying to make a python script that will play videos and I found this file that download’s Youtube videos. I am not entirely sure what is going on and I can’t figure out this error.

Error:

AttributeError: 'NoneType' object has no attribute 'group'

Traceback:

Traceback (most recent call last):
  File "youtube.py", line 67, in <module>
    videoUrl = getVideoUrl(content)
  File "youtube.py", line 11, in getVideoUrl
    grps = fmtre.group(0).split('&amp;')

Code snippet:

(lines 66-71)

content = resp.read()
videoUrl = getVideoUrl(content)

if videoUrl is not None:
    print('Video URL cannot be found')
    exit(1)

(lines 9-17)

def getVideoUrl(content):
    fmtre = re.search('(?<=fmt_url_map=).*', content)
    grps = fmtre.group(0).split('&amp;')
    vurls = urllib2.unquote(grps[0])
    videoUrl = None
    for vurl in vurls.split('|'):
        if vurl.find('itag=5') > 0:
            return vurl
    return None

asked Feb 26, 2013 at 2:00

Dave's user avatar

2

The error is in your line 11, your re.search is returning no results, ie None, and then you’re trying to call fmtre.group but fmtre is None, hence the AttributeError.

You could try:

def getVideoUrl(content):
    fmtre = re.search('(?<=fmt_url_map=).*', content)
    if fmtre is None:
        return None
    grps = fmtre.group(0).split('&amp;')
    vurls = urllib2.unquote(grps[0])
    videoUrl = None
    for vurl in vurls.split('|'):
        if vurl.find('itag=5') > 0:
            return vurl
    return None

answered Feb 26, 2013 at 2:02

Ian McMahon's user avatar

Ian McMahonIan McMahon

1,65011 silver badges13 bronze badges

1

You use regex to match the url, but it can’t match, so the result is None

and None type doesn’t have the group attribute

You should add some code to detect the result

If it can’t match the rule, it should not go on under code

def getVideoUrl(content):
    fmtre = re.search('(?<=fmt_url_map=).*', content)
    if fmtre is None:
        return None         # if fmtre is None, it prove there is no match url, and return None to tell the calling function 
    grps = fmtre.group(0).split('&amp;')
    vurls = urllib2.unquote(grps[0])
    videoUrl = None
    for vurl in vurls.split('|'):
        if vurl.find('itag=5') > 0:
            return vurl
    return None

answered Feb 26, 2013 at 2:04

Tanky Woo's user avatar

Tanky WooTanky Woo

4,7949 gold badges41 silver badges75 bronze badges

Just wanted to mention the newly walrus operator in this context because this question is marked as a duplicate quite often and the operator may solve this very easily.


Before Python 3.8 we needed:

match = re.search(pattern, string, flags)
if match:
    # do sth. useful here

As of Python 3.8 we can write the same as:

if (match := re.search(pattern, string, flags)) is not None:
    # do sth. with match

Other languages had this before (think of C or PHP) but imo it makes for a cleaner code.


For the above code this could be

def getVideoUrl(content):
    if (fmtre := re.search('(?<=fmt_url_map=).*', content)) is None:
        return None
    ...

answered May 22, 2019 at 11:03

Jan's user avatar

JanJan

41.5k8 gold badges50 silver badges78 bronze badges

just wanted to add to the answers, a group
of data is expected to be in a sequence, so you can
match each section of the grouped data without
skipping over a data because if a word is skipped from a
sentence, we may not refer to the sentence as one group anymore, see the below example for more clarification, however, the compile method is deprecated.

msg = "Malcolm reads lots of books"

#The below code will return an error.

book = re.compile('lots books')
book = re.search(book, msg)
print (book.group(0))

#The below codes works as expected

book = re.compile ('of books')
book = re.search(book, msg)
print (book.group(0))

#Understanding this concept will help in your further 
#researchers. Cheers.

answered May 13, 2020 at 13:46

GitHubRobot's user avatar

The Python error “AttributeError: ‘NoneType’ object has no attribute ‘group’” simply means you’re trying to access an attribute called “group” on a variable that contains the special type None. None in Python just means there’s nothing there, and is equivalent to “null” in other languages.

The most common cause of “AttributeError: ‘NoneType’ object has no attribute ‘group’” is trying to access groups in a regex match that returned None. Also, some googletrans versions may misuse regular expressions internally which can lead to this error.

Let’s take a look at how to avoid this error.

Preventing “AttributeError: ‘NoneType’ object has no attribute group”

To prevent this error, we first have to understand it. We’ll start by reproducing it in the simplest way possible. Then, we’ll take a look at a couple real-world causes of this error and ways to fix them. The most common cause, not checking for a valid match before trying to access it, boils down to simply doing proper None checks first. The other cause, Python packages misbehaving, means we need to update them.

Let’s try to reproduce the error first.

Reproducing the AttributeError

Since this is an AttributeError, which we’ve seen plenty of in the past, we already know it means that we’re trying to access something that isn’t there. In our case, we’re trying to access the attribute “group” on a NoneType object. NoneType objects in Python simply means there’s nothing there. Nobody’s home. Nada. Zip.

Below is the simplest way to reproduce the error:

some_string = None
some_string.group()

When run, we’ll see the following output:

Traceback (most recent call last):
  File "/home/user/main.py", line 2, in <module>
    some_string.group()
AttributeError: 'NoneType' object has no attribute 'group'

Now, your situation probably isn’t literally creating a variable containing None and then trying to access a method on it called “group”. Below, we’ll take a look at some causes that probably led you here.

2 Real-World Causes of “AttributeError: ‘NoneType’ object has no attribute group”

While this error may come up in other situations, the most common causes of it are:

  • You did something wrong while using the re package
  • Your googletrans package is out of date

That last one may seem pretty specific, but lots of people have been having issues with it lately. Luckily for your, there’s an easy fix! Let’s first look at the most common cause, which is doing bad things with the re package.

When Using the re Python Package

Regular expressions are hard to learn. Once you learn them, you then have to deal with clunky implementations such as Python’s re package. Unlike other scripting languages, regular expressions are not first class citizens in Python. You have to cram them into a regular string object and, optionally, prefix the pattern with an “r” so you don’t have to double escape the backslash (which is used liberally as a special character in regular expressions).

On top of all that, once you have the expression correct, you might not find what you’re looking for. New programmers will often forget to check if there’s a match first before trying to use it.

Below, we’ll do a simple match on a simple string and see what happens:

import re
text = "foo bar 123 baz"
pattern = r".* ([4-9]+) .*"
matches = re.match(pattern, text)
print(matches.group(1))

Obviously, if you know anything about regular expressions, you already know this isn’t going to find anything. In the above example, we’re trying to find one or more digits in the range of 4 through 9 in the string “foo bar 123 baz”. No such digits exist, so we’re not going to find anything.

But, like the newbies that we are, we’re going to try to access a match without checking for None first. The result is the error we’ve been discussing:

Traceback (most recent call last):
  File "/home/user/main.py", line 7, in <module>
    print(matches.group(1))
AttributeError: 'NoneType' object has no attribute 'group'

D’oh! To fix this, we can simply use the right pattern:

import re
text = "foo bar 123 baz"
pattern = r".* (d+) .*"
matches = re.match(pattern, text)
print(matches.group(1))
# -> 123

Nice, it works. But that’s not the right answer. The right way to do it would be to check for None first so that we can always avoid this problem, even if we got the pattern wrong:

import re
text = "foo bar 123 baz"
pattern = r".* ([4-9]+) .*"
matches = re.match(pattern, text)
if matches:
    print(matches.group(1))
else:
    print("No matches!")
# -> "No matches!"

As you can see, a simple if statement will suffice. Since None is “falsy” (evaluates to false) in Python, we can just evaluate the returned matches as if it were a boolean to see if there’s anything there.

Some people might suggest surrounding the use of the returned matches in a try/except block, but that’s actually not best practice if you know you might not get any matches back. You shouldn’t use exceptions to control program flow! Exceptions are meant to be, well, exceptional.

When Using the googletrans Python Package

Another common cause of this is using an old googletrans package. The package googletrans gives you access to the Google Translate API. It’s incredibly useful! Especially since you don’t need an authorization token or anything like you do with other Google cloud services.

Unfortunately, in recent months, the default PyPi package has been throwing this error every time you try to translate something. The pip install command below is enough to install the bad package:

Now, we can attempt a simple translation of “Hello, how are you?” in Spanish:

from googletrans import Translator
translator = Translator()
print(translator.translate("hola como estas", dest="en"))

Seems simple enough, right? Well, as we’re about to find out, this version of googletrans is broken:

Traceback (most recent call last):
  File "/home/user/main.py", line 4, in <module>
    print(translator.translate("hola como estas", dest="en"))
  File "/home/user/.local/lib/python3.9/site-packages/googletrans/client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "/home/user/.local/lib/python3.9/site-packages/googletrans/client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "/home/user/.local/lib/python3.9/site-packages/googletrans/gtoken.py", line 194, in do
    self._update()
  File "/home/user/.local/lib/python3.9/site-packages/googletrans/gtoken.py", line 62, in _update
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

If you look through the stack trace above, you’ll see that the problem is still caused by trying to access a regular expression capture group without checking for None first. It’s just buried deep within the googletrans package rather than in your code.

See? It’s not even your fault. But that’s not going to make you feel better for long. Let’s fix it!

Fix 1: install googletrans 4.0.0-rc1

Lucky for us, Google has a release candidate that stops the “AttributeError: ‘NoneType’ object has no attribute ‘group’” error from occurring. Simply install the new version with the pip command below:

pip3 install googletrans==4.0.0-rc1

Now, when we run the same code as above, we’ll actually get a translation!

Translated(src=es, dest=en, text=Hi, how are you, pronunciation=None, extra_data="{'confiden...")

Cool! You can clean up this output by changing the print statement to the following:

print(translator.translate("hola como estas", dest="en").text)

That will give you just the translation.

Next, we’ll look at another potential fix with a 3rd party Python package.

Fix 2: install google_trans_new

Note: this no longer works. As of mid 2021, the google_trans_new package is having problems as well. There’s an open ticket for it on GitHub.

There’s also a 3rd party package called google_trans_new that used to solve this problem. It doesn’t work currently, but for future reference, it can be installed with:

pip install google_trans_new

Once installed, it’s usage is very similar to googletrans:

from google_trans_new import google_translator
translator = google_translator()
print(translator.translate("hola como estas", lang_src="es", lang_tgt="en"))

Unfortunately though, the following error will occur no matter what:

Traceback (most recent call last):
  File "/home/user/main.py", line 4, in <module>
    print(translator.translate("hola como estas", lang_src="es", lang_tgt="en"))
  File "/home/user/.local/lib/python3.9/site-packages/google_trans_new/google_trans_new.py", line 188, in translate
    raise e
  File "/home/user/.local/lib/python3.9/site-packages/google_trans_new/google_trans_new.py", line 152, in translate
    response = json.loads(response)
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 340, in decode
    raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 464 (char 463)

It looks like it’s not handling the JSON response from the Google API correctly. If you’re feeling froggy, you can go to their GitHub project and submit a pull request for it!

Conclusion

That took a while. We covered the root cause of “AttributeError: ‘NoneType’ object has no attribute ‘group’” which turns out to be simply accessing “group” on a None object. But since that’s probably not what you were doing, we also looked at a couple of the other usual suspects: re and googletrans. But inside, the issue with googletrans is still re. So really, it’s always re that’s the cause of this.

Happy coding and remember to check for None!

Summary: NoneType attribute error occurs when the type of object being referenced is None. To handle this error you can either use the try-except blocks or you may also use if-else statements according to your requirement.

In this article, you will learn about attribute errors with the help of numerous scenarios/examples where you come across such errors and how to deal with the error. So, without further delay let us dive into our discussion.

How To Fix Attribute Error: ‘NoneType’ Object Has No Attribute ‘Group’?

❖ Attribute Error

Before we learn how to resolve the attribute error, it is important to understand what is an attribute error or why do we encounter an attribute error?

What is an attribute in Python?

In Python, an attribute can be considered as any property associated with a particular type of object. For example, insert, sort, and remove are some of the attributes of the list type object.

This brings us to the question, what is an attribute error?

Whenever you try to reference an invalid attribute, you get an "attribute error". 

In other words, attribute errors are raised when you try to access a certain attribute of a particular object, however, the object does not possess the called attribute. Let us understand this with reference to our previous example of the list tye object. Since insert is an attribute of the list type object, we will face no issues while using insert with a list. However, a tuple does not possess the insert attribute. Hence, if you try to reference the insert attribute with respect to a tuple, you will get an attribute error.

Example:

tup = ("Square", "Rectangle", "Pentagon")
tup.insert(2,'circle')
print(tup)

Output:

AttributeError: 'tuple' object has no attribute 'insert'

This brings us to the next phase of our discussion where we will discuss ‘NoneType’ object has no attribute ‘xyz’ error.

There may be cases where you encounter an error that says:

AttributeError: 'NoneType' object has no attribute 'something'

Let us try to dissect our problem and understand the scenarios which can cause such AttributeError.

So, what is NoneType supposed to mean?

NoneType means that whatever class or object you are trying to access is None. Therefore, whenever there is a function call or an assignment with regards to that object, it will fail or return an unexpected output.

You may encounter such an attribute error in numerous scenarios. Let us have a look at some scenarios where you may come across such an error.

Scenario 1

x1 = None
print(x1.something)

Output:

  File "D:/PycharmProjects/Errors/attribute_error.py", line 2, in <module>
    print(x1.something)
AttributeError: 'NoneType' object has no attribute 'something'

Scenario 2

x1 = None
x1.some_attribute = "Finxter"

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/Errors/attribute_error.py", line 2, in <module>
    x1.some_attribute = "FINXTER"
AttributeError: 'NoneType' object has no attribute 'some_attribute'

Scenario 3

def foo(a):
    if a < 0:
        return a


y = foo(5)
print(y.func())

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/Errors/attribute_error.py", line 7, in <module>
    print(y.func())
AttributeError: 'NoneType' object has no attribute 'func'

Explanation: In the above code, the function call is not returning anything or in other words, it is returning None and we are trying to access a non-existing attribute of that None type object.

Solution 1 : Use if-else Statements

To avoid the NoneType attribute error you can use the if-else statements accordingly to eliminate or skip the situation where the returned object type is None.

x1 = None
if x1 is not None:
    x1.some_attribute = "Finxter"
else:
    print("The type of x1 is ", type(x1))

Output:

The type of x1 is  <class 'NoneType'>

Solution 2 : Use try-except blocks (Exception Handling)

Another workaround to deal with an attribute error is to use exception handling i.e. the try and except blocks.

Example:

def foo(a):
    if a < 0:
        return a


x = foo(-1)
y = foo(5)
try:
    print(x)
    print(y.func()) # Raises an AttributeError
except AttributeError:
    print("No such Attribute!")

Output:

-1
No such Attribute!

❖ How To Fix Error: ‘NoneType’ Object Has No Attribute ‘Group’?

Since we have already discussed the reasons for getting a NoneType attribute error and the ways to handle such errors, let us have a look at a very commonly asked question based on our earlier discussion.

AttributeError: ‘NoneType’ object has no attribute ‘group’

Example:

import re

# Search for an upper case "S" character in the beginning of a word, and print the word:

txt = "The rain in Spain"
for i in txt.split():
    x = re.match(r"bSw+", i)
    print(x.group())

Output:

Traceback (most recent call last):
  File "D:/PycharmProjects/Errors/attribute_error.py", line 9, in <module>
    print(x.group())
AttributeError: 'NoneType' object has no attribute 'group'

Reason:

The code encounters an attribute error because in the first iteration it cannot find a match, therefore x returns None. Hence, when we try to use the attribute for the NoneType object, it returns an attribute error.

Solution:

Neglect group() for the situation where x returns None and thus does not match the Regex. Therefore use the try-except block such that the attribute error is handled by the except block. The following code will further clarify things:

import re


txt = "The rain in Spain"
for i in txt.split():
    x = re.match(r"bSw+", i)
    try:
        print(x.group())
    except AttributeError:
        continue

Output:

Spain

Note: The above example deals with regex. Do you want to master the regex superpower? Check out our book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

Conclusion

The key areas covered in this article were:

  • What is an attribute error?
  • What is a NoneType attribute error?
  • The scenarios when we encounter attribute errors.
  • Methods to deal with attribute error:
    • using if-else
    • using try-except
  • How To Fix Error: ‘NoneType’ Object Has No Attribute ‘Group’?

I hope you enjoyed this article and learned about attribute errors. Please stay tuned and subscribe for more interesting articles!

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!

shubham finxter profile image

I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.

You can contact me @:

UpWork
LinkedIn

  1. Cause of AttributeError: 'NoneType' object has no attribute 'group' in Python
  2. Use try-except to Solve AttributeError: 'NoneType' object has no attribute 'group' in Python
  3. Use if-else to Solve AttributeError: 'NoneType' object has no attribute 'group' in Python

Solve AttributeError: 'Nonetype' Object Has No Attribute 'Group' in Python

Python regular expression (regex) matches and extracts a string of special characters or patterns. In Python, the regex AttributeError: 'NoneType' object has no attribute 'group' arises when our regular expression fails to match the specified string.

In this article, we will take a look at possible solutions to this type of error.

Cause of AttributeError: 'NoneType' object has no attribute 'group' in Python

Whenever we define a class or data type, we have access to the attributes associated with that class. But suppose we access the attributes or properties of an object not possessed by the class we defined.

In that case, we encounter the AttributeError saying the 'NoneType' object has no attribute 'group'. The NoneType refers to the object containing the None value.

This type of error also occurs in a case when we set a variable initially to none. The following program is for searching for the uppercase F at the beginning of a word.

Example Code:

#Python 3.x
import re
a="programmig is Fun"
for i in a.split():
    b=re.match(r"bFw+", i)
    print(b.group())

Output:

#Python 3.x
AttributeError                            Traceback (most recent call last)
C:UsersLAIQSH~1AppDataLocalTemp/ipykernel_2368/987386650.py in <module>
      3 for i in a.split():
      4     b=re.match(r"bFw+", i)
----> 5     print(b.group())

AttributeError: 'NoneType' object has no attribute 'group'

This error is raised because the regular expression cannot match the specified letter in the string in the first iteration. Thus, when we access group(), the compiler shows an AttributeError because it belongs to the object of type None.

Use try-except to Solve AttributeError: 'NoneType' object has no attribute 'group' in Python

One method to eliminate this error is using exception handling in your code. In this way, the except block will handle the error.

Now consider the previous program, and we will add the try-except block as follows.

Example Code:

#Python 3.x
import re
a="programmig is Fun"
for i in a.split():
    b=re.match(r"bFw+", i)
    try:
        print(b.group())
    except AttributeError:
        continue

Output:

Now we see that our program works fine. The keyword continue is used here to skip where b returns none, jumps to the next iteration, and searches for a word that begins with F.

Hence, the term Fun prints in the output.

Use if-else to Solve AttributeError: 'NoneType' object has no attribute 'group' in Python

Another simple solution to avoid the 'NoneType' object has no attribute 'group' error is to use the if-else statement in your program. The following program checks the numbers in the string ranging from 1 to 5.

Since there is no number to match the regular expression, it results in an AttributeError. But using the if-else block, we can avoid the error.

If the condition is not satisfied, the statement in the else block executes when no matches are found.

#Python 3.x
import re
a = "foo bar 678 baz"
x = r".* ([1-5]+) .*"
matches = re.match(x, a)
if matches:
    print(matches.group(1))
else:
    print("No matches!")

Output:

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.

Already on GitHub?
Sign in
to your account


Closed

halleyshx opened this issue

Nov 21, 2017

· 40 comments

Comments

@halleyshx

My script like this:
#-— coding:utf-8 —
from googletrans import Translator
import sys
import io

translator = Translator()
tanstext = u’我们’
tran_ch = translator.translate(tanstext ).text
print tran_ch
###############
yesterday this is ok and no problem,but today I run my script without internet, show some problem.And I run the script in the internet environment, but it’s show same problem,can’t run.
The cmd show the Traceback like this:
Traceback (most recent call last):
File «D:JDstoryworkstorytranslation-projectfiletocuttrans-test.py», line
10, in
tran_ch = translator.translate(tanstext).text
File «D:softwarePython27libsite-packagesgoogletransclient.py», line 132,
in translate
data = self._translate(text, dest, src)
File «D:softwarePython27libsite-packagesgoogletransclient.py», line 57,
in _translate
token = self.token_acquirer.do(text)
File «D:softwarePython27libsite-packagesgoogletransgtoken.py», line 180,
in do
self._update()
File «D:softwarePython27libsite-packagesgoogletransgtoken.py», line 59,
in _update
code = unicode(self.RE_TKK.search(r.text).group(1)).replace(‘var ‘, »)
AttributeError: ‘NoneType’ object has no attribute ‘group’
#########################
That’s why? Thank you so much!

@Andy671

Have you found a solution?

@Larkina

This means google banned your IP.

Erfan3Black, tokageki, elonmusk14, MrPotato374, Grommish, wok1909, Patitotective, Hunbao0703, kccchiu, sh3ldr0id, and 2 more reacted with thumbs down emoji

@Darkblader24

Wrong, this happens when Google directly sends you the raw token. They do this for a short time after maintenance, not sure why.

@MTL1991

Hi,

from yesterday I have this «error». How do you think that I could fix it. I just created other server to execute my code and the result it’s the same 🙁

Thanks

@Darkblader24

See here for the fix: #78

@MTL1991

@ariefsibuea

how to use it for translation code above?

@romanseer

go to browser with Google Translate page, try to translate Hello World =)
if you see Error translated — your IP are banned

@ariefsibuea

I have tried to translate from Google Translate page and it works. But when I try code above it failed with same error as shown above.

@ariefsibuea

See here for the fix: #78

Can I use the code with the translation code by @halleyshx ?

@hrishikeshpatel

After applying #78 I got below error. Please help

380             obj, end = self.scan_once(s, idx)
381             except StopIteration:
382             raise ValueError("No JSON object could be decoded")
383         return obj, end

ValueError: No JSON object could be decoded

@joaonetto

Looking other places, probably the issue is around a Regex from Google Translate than they use to working on.

Take a look in: pndurette/gTTS#138

@Maldus512

See here for the fix: #78

Apologies, I just installed this library via pip and encountered this error. How should I proceed to apply said fix?

@luapp

hello, I try today to use the gtts on python but is not working
can somebody help me please ?

the error is:

Exception has occurred: OSError
[Errno 22] Invalid argument: ‘C:test.mp3’
File «C:UsersAdministratorDesktopSpeech-Recognition.py», line 39, in
speech.save(«C:test.mp3»)

My code:

import speech_recognition as sr
from gtts import gTTS
import os
import playsound

while True:

command = 0
speech = 0

mic = sr.Microphone()
r = sr.Recognizer()
with mic as source:
print(«Calibrate Microphone»)
print(«Please wait…»)
r.adjust_for_ambient_noise(source, duration=1)
print(«listening…»)
audio = r.listen(source)

try:
command = (r.recognize_google(audio))
print(«you said:»+command)

except sr.UnknownValueError:
print(«»)

except sr.RequestError:
print(«»)

if «hello» in command:
print(«hello»)
speech = gTTS(«hello», lang=»en»)
if os.path.exists(«C:test.mp3»):
print(«file exist»)
playsound.playsound(«C:test.mp3», True)
else:
print(«saving new mp3 sound»)
speech.save(«C:test.mp3»)
playsound.playsound(«C:test.mp3», True)

@joaonetto

@feifanhanmc

@algoscale1

@Darkblader24 My IP is also getting blocked after using the pull request [(https://github.com//pull/78)], although it resolved the «None Type» issue. It happens after 250 requests or something, I have even tried on a different server, the IP is continuously getting blocked after few requests. Earlier I could make thousands of requests and my IP never got blocked. The new pull request has messed up something, any idea?

@ramya-ramanathan

Quick question: What is the error you get when your IP is blocked?

Is it ValueError: No JSON object could be decoded ?

@astariul

The error when the IP is blocked is Expecting value: line 1 column 1 (char 0)

Any idea how to unblock my IP address ?

@1010Manoj

@ramya-ramanathan I am getting ValueError: No JSON object could be decoded
what is this for???

@SmartDev-0205

Hello
I get ‘NoneType’ object has no attribute ‘group’
I have tried this
$ pip uninstall googletrans
$ git clone https://github.com/BoseCorp/py-googletrans.git
$ cd ./py-googletrans
$ python setup.py install
But get same issue
Please help me

@bastienboutonnet

I’ve been getting this as well on a recent install of googletrans in a fresh venv:

  File "<truncated_for_privacy>/lib/python3.6/site-packages/googletrans/client.py", line 182, in translate
    data = self._translate(text, dest, src, kwargs)
  File "<truncated_for_privacy>/lib/python3.6/site-packages/googletrans/client.py", line 78, in _translate
    token = self.token_acquirer.do(text)
  File "<truncated_for_privacy>/lib/python3.6/site-packages/googletrans/gtoken.py", line 194, in do
    self._update()
  File "<truncated_for_privacy>/lib/python3.6/site-packages/googletrans/gtoken.py", line 62, in _update
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

@yoyoidea

Hello
I get ‘NoneType’ object has no attribute ‘group’
I have tried this
$ pip uninstall googletrans
$ git clone https://github.com/BoseCorp/py-googletrans.git
$ cd ./py-googletrans
$ python setup.py install
But get same issue
Please help me

me, too.

@Hamilkar247

ksmin23

added a commit
to ksmin23/aws-rss-feed-trans-bot
that referenced
this issue

Nov 8, 2020

@ksmin23

ksmin23

added a commit
to ksmin23/aws-blog-trans-bot
that referenced
this issue

Nov 8, 2020

@ksmin23

@waelmas

Still having this issue too frequently. Impacting our production.

For days we thought we’ve been doing something wrong…

@ashishalakhani

I am seeing this issue as well. I see it on dev and staging environment but not in production.

@markklick206

Getting the same «Attribute Error» after GoogleTrans had been working great for months…

  File "C:Anaconda3libsite-packagesgoogletransgtoken.py", line 65, in _update
    code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

@mateoToquica

I’ve been using this library to do research work, where I have to translate several images, at first I thought it was an error in the images because they have different edges and colors, but then I used a time delay for some images that did not work and suddenly they started translating. The problem is that it does not work for all the images, below I show how I use the delay

def translateImg(src):
    img = cv2.imread(src)
    text = pytesseract.image_to_string(img, lang='ara')
    print(text)
    time.sleep(10) # sleep the aplication 10 seconds
    translator = Translator()
    result = translator.translate(text)
    print(result.text)
for x in range(1,28):
    translateImg('../resources/photos/annunciAmaq1/img ('+str(x)+').jpg')

@jmagdeska

I’m also getting the same issue, any fix for this?

File "/home/anaconda3/lib/python3.7/site-packages/googletrans/gtoken.py", line 62, in _update
    code = self.RE_TKK.search(r.text).group(1).replace('var ', '')
AttributeError: 'NoneType' object has no attribute 'group'

I’m using Python 3.7.3 on Ubuntu 20.04 machine

@MartinVinter

Hey there,

In another 2 years old thread talking about this issue (which sadly, I cannot find again) it was mentioned that upgrading GoogleTrans helps. It has helped for me too, but only for a short while. In other old threads I have found, it was mentioned, that an older version of the issue was related to a problem with an API key, token or similar. So my theory is that I get another key if I update. Even when there isn’t a new version, Anaconda will re-download and install the package. At least you can give it a shot. It is quite easy — run this in Anaconda:

pip install git+https://github.com/BoseCorp/py-googletrans.git --upgrade

@sergiomora03

Hi, I get the same error.

Python version 3.8.3

@sergiomora03

Hey there,

In another 2 years old thread talking about this issue (which sadly, I cannot find again) it was mentioned that upgrading GoogleTrans helps. It has helped for me too, but only for a short while. In other old threads I have found, it was mentioned, that an older version of the issue was related to a problem with an API key, token or similar. So my theory is that I get another key if I update. Even when there isn’t a new version, Anaconda will re-download and install the package. At least you can give it a shot. It is quite easy — run this in Anaconda:

pip install git+https://github.com/BoseCorp/py-googletrans.git --upgrade

It´s not work. Still the error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-f71bcb40be3a> in <module>
----> 1 translator.translate('Hola Mundo')

~Anaconda3libsite-packagesgoogletransclient.py in translate(self, text, dest, src)
    170 
    171         origin = text
--> 172         data = self._translate(text, dest, src)
    173 
    174         # this code will be updated when the format is changed.

~Anaconda3libsite-packagesgoogletransclient.py in _translate(self, text, dest, src)
     73             text = text.decode('utf-8')
     74 
---> 75         token = self.token_acquirer.do(text)
     76         params = utils.build_params(query=text, src=src, dest=dest,
     77                                     token=token)

~Anaconda3libsite-packagesgoogletransgtoken.py in do(self, text)
    184 
    185     def do(self, text):
--> 186         self._update()
    187         tk = self.acquire(text)
    188         return tk

~Anaconda3libsite-packagesgoogletransgtoken.py in _update(self)
     63 
     64         # this will be the same as python code after stripping out a reserved word 'var'
---> 65         code = unicode(self.RE_TKK.search(r.text).group(1)).replace('var ', '')
     66         # unescape special ascii characters such like a x3d(=)
     67         if PY3:  # pragma: no cover

AttributeError: 'NoneType' object has no attribute 'group'

@BoyuChen118

You can simply overcome this issue by using error handling like so:

while True:
    try:
       # you translation code here
    except:
        print(Exception)
        continue
    break

@ashishalakhani

You can simply overcome this issue by using error handling like so:

while True:
    try:
       # you translation code here
    except:
        print(Exception)
        continue
    break

Won’t this go in infinite loop?

@NicoCaldo

You can simply overcome this issue by using error handling like so:

while True:
    try:
       # you translation code here
    except:
        print(Exception)
        continue
    break

Won’t this go in infinite loop?

For some reason, at a certain point, the translation succeed, at least, from my experience

@jmagdeska

You can simply overcome this issue by using error handling like so:

while True:
    try:
       # you translation code here
    except:
        print(Exception)
        continue
    break

Won’t this go in infinite loop?

Yes, issue is not solved, the program goes to infinite loop.

@ashishalakhani

I don’t think we can rely on this library for production use. Any other free alternative?

@NicoCaldo

@jmagdeska

I don’t think we can rely on this library for production use. Any other free alternative?

It works like a charm for me https://github.com/lushan88a/google_trans_new

Thank you for sharing this resource, I confirm it works without problems so far.

@ohMuzzy

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Attempting to start mysql service xampp ошибка
  • Attempt to read from address 0x00000000 prey ошибка