当我尝试 运行 以下代码时,我收到此错误 'str' object has no attribute 'text'

I receive this error 'str' object has no attribute 'text' when I try to run the following code

我删除了 .text 并且刚刚写了 peter_pan.split() 但我不确定输出是否正确。

import requests
from nltk import FreqDist

url = "https://www.gutenberg.org/files/16/16-0.txt"
peter_pan = requests.get(url).text

peter_pan_words = peter_pan.text.split()

word_frequency = FreqDist(peter_pan_words)

freq = word_frequency.most_common(3)[2][1]


print(freq)

您的这部分代码:

peter_pan = requests.get(url).text

当您调用 .text 时,您正在将对象转换为字符串。因此,由于它现在是一个字符串,您不能再次对其调用 .text。只需更改:

peter_pan_words = peter_pan.text.split()

peter_pan_words = peter_pan.split()

你在做什么:

peter_pan = requests.get(url).text

您使用的textrequests.get返回的响应对象的方法。此方法returns 一个字符串(包含页面内容)。这一切都很好。

但是,您正在做:

peter_pan_words = peter_pan.text.split()

这次您尝试做的是访问 str 对象的 text 方法,但是 str 没有任何名为 text 的方法。如果您执行 print(dir(peter_pan)),您将看到可供您访问的属性 (methods/properties)。您应该会看到类似于以下内容的内容:

['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

你会看到 text 不是其中之一(这就是你得到错误的原因),但你也会看到 split 在那里 - 事实上你需要做的是直接调用split

peter_pan_words = peter_pan.split()