gpt4 book ai didi

Python列表没有isalpha()

转载 作者:行者123 更新时间:2023-11-30 21:54:14 24 4
gpt4 key购买 nike

我尝试读取包含以下数据的文本文件并说明其数据类型:

这是txt文件中的数据

        9yr14z1jdnh01ou8d38        , rcsfhuivhqgpgabxd, szumg5l7lyc30wimkah4, 1345, yfeporesumr, 1313.670598592, 1384.35266, gklxmzulyylpuhkabawhuhtcxjy, ugwulzqwhld, 8422, 8728.054385, 1675,  9xuxp5l7trq50l6psgw058aqacs9n , 2080.01345, ppznnnmherwktxugprysryj, 4295, 6992,  g0aa4yh2btxc6ta959p9o

输出应该是这样的:

youruasdifafasd - alphabetical strings
127371237 - integer
asdfka12348fas - alphanumeric
13123.123 - real numbers
asjdfklasdjfklaasf - alphabetical strings
123192u3kjwekhf - alphanumeric

我尝试显示它们的数据类型,但这是错误:

AttributeError: 'list' object has no attribute 'isalpha'

这是我到目前为止的代码:

import numbers
import os
import string
import pandas as pd

data = []
with open('output.txt') as file:
for row in file:
# row = row.strip()
row = row.replace(" ", "")
data.append(row.split(","))
# print(data)

for x in data:
# print (x)
if x.isalpha():
print (x + " - alphabetical strings")
elif x.isalnum():
print (x + " - alphanumeric")
elif isinstance(x, numbers.Integral):
print (x + " - integer")
else:
print (x + " - float")

最佳答案

问题是您的列表有 2 个维度,并且您在 for 循环中得到一个列表类型。如果您在 with 语句之后打印数据,您可以看到 2 个维度(嵌套列表)。

print(data)
# [['9yr14z1jdnh01ou8d38', 'rcsfhuivhqgpgabxd', 'szumg5l7lyc30wimkah4', ...]]

如果将 .append() 方法更改为 .extend() 方法,则可以解决此问题。

我已经根据您的原始实现创建了一个工作版本。我使用了您在问题中提到的 output.txt

我不必将 data 变量定义为空列表。您应该阅读完整的文件并删除空格并根据 , 分隔符拆分字符串。以下行执行此操作:data = file.read().replace("", "").split(",")

在这个解决方案中,您有一个一维列表,如果您对其进行迭代,您将获得单个元素。如果打印 data 变量,您可以看到:['9yr14z1jdnh01ou8d38', 'rcsfhuivhqgpgabxd', 'szumg5l7lyc30wimkah4', ...]。这意味着您可以在 for 循环中逐一获取元素,isalpha()isalnum() 将按预期工作。

代码:

import numbers

with open("output.txt") as file:
data = file.read().replace(" ", "").split(",")

for x in data:
if x.isalpha():
print("{} - alphabetical strings".format(x))
elif x.isalnum():
print("{} - alphanumeric".format(x))
elif isinstance(x, numbers.Integral):
print("{} - integer".format(x))
else:
print("{} - float".format(x))

输出:

>>>python3 test_file.py 
9yr14z1jdnh01ou8d38 - alphanumeric
rcsfhuivhqgpgabxd - alphabetical strings
szumg5l7lyc30wimkah4 - alphanumeric
1345 - alphanumeric
yfeporesumr - alphabetical strings
1313.670598592 - float
1384.35266 - float
gklxmzulyylpuhkabawhuhtcxjy - alphabetical strings
ugwulzqwhld - alphabetical strings
8422 - alphanumeric
8728.054385 - float
1675 - alphanumeric
9xuxp5l7trq50l6psgw058aqacs9n - alphanumeric
2080.01345 - float
ppznnnmherwktxugprysryj - alphabetical strings
4295 - alphanumeric
6992 - alphanumeric
g0aa4yh2btxc6ta959p9o - alphanumeric

关于Python列表没有isalpha(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59387777/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com