Traceback (most recent call last): File "D:\Project\Test01.py", line 5, in <module> print(name,len(5)) ^^^^^^ TypeError: object of type 'int' has no len()
时间: 2023-12-03 11:44:29 浏览: 26
这个错误是因为你尝试获取一个整数类型对象的长度。在 Python 中,len() 函数只能用于序列(如字符串、列表、元组等),而不能用于数字类型。
请检查你的代码,看看是否有意外传递了一个数字对象给 len() 函数。如果你想要获取一个数字的位数,可以将其转换成字符串,然后使用 len() 函数。例如:
```
num = 12345
num_str = str(num)
print(len(num_str)) # 输出 5
```
希望能帮到你!
相关问题
Traceback (most recent call last): File "C:\Users\test\PycharmProjects\pythonProject\DIDI数据写入CSV.py", line 38, in <module> print("talkid:", talk_id) ^^^^^^^ NameError: name 'talk_id' is not defined
这个错误是因为在 `print("talkid:", talk_id)` 这一行中,`talk_id` 变量没有被定义。可能是因为在你的代码中,没有成功地从源代码中提取到 `talk_id`。
要解决这个问题,你可以在使用 `find_previous` 方法之前,添加一个条件判断来确保找到了目标元素。例如:
```python
from bs4 import BeautifulSoup
html_content = '''
[talkid:138031362]2014年4月20日 04:45:45 , <span class="hint-success" data-hint"">434343</span> 向 <span class="hint-success" data-hint="">123456</span> 发送 音频 :[<a href="files/f/f123fsasfsfsjdfrhf_n.m4a"]>音频</a>
<p>
()</p>[talkid:138031351]204年4月20日 03:55:45 , <span class="hint-success" data-hint"">3507154</span> 向 <span class="hint-success" data-hint="">1359075</span> 发送 我们已经是好友了,开始聊天吧!
<p>
()</p>
'''
soup = BeautifulSoup(html_content, 'html.parser')
messages = soup.find_all('p')
for message in messages:
talk_id_tag = message.find_previous('a')
if talk_id_tag:
talk_id = talk_id_tag.text.strip()[1:]
time = message.contents[0].strip().split(',')[0][1:]
send_phone = message.find('span', class_='hint-success').text.strip()
receive_phone = message.find_all('span', class_='hint-success')[1].text.strip()
content_tag = message.find('a')
if content_tag:
content = content_tag['href']
content_type = '音频'
else:
content = message.text.strip()
content_type = '文本'
print("talkid:", talk_id)
print("时间:", time)
print("发送号码:", send_phone)
print("接收号码:", receive_phone)
print("发送内容:", content)
print("内容类型:", content_type)
print()
```
在这个例子中,我们添加了一个条件判断 `if talk_id_tag:` 来确保 `talk_id_tag` 不为空,只有当找到目标元素时才进行提取操作。这样可以避免 `NameError` 错误。
上面代码报错Traceback (most recent call last): File "C:\Users\一\PycharmProjects\pythonProject\test.py", line 69, in <module> if '我喜欢你' in message: ^^^^^^^ NameError: name 'message' is not defined
这个错误提示说的是 `message` 这个变量没有定义,可能是因为你在代码中使用了这个变量,但是没有给它赋值。你需要先定义 `message` 变量,然后才能在后续的代码中使用它。比如:
```
message = input("请输入消息:")
if '我喜欢你' in message:
print("我也喜欢你!")
else:
print("我不太理解你的意思。")
```
这样就可以避免这个错误了。