【问题标题】:Converting string array into int array in python在python中将字符串数组转换为int数组
【发布时间】:2021-07-01 12:50:25
【问题描述】:

我使用一个 txt 文件,其中一些坐标以这种格式存储在脚本中:

[(310, 71), (466, 145), (432, 285), (238, 289), (196, 150)]

从另一个脚本启动读取文件,我需要将此输入作为整数,以便我可以将其用作输入来制作 np.array。

但我得到的是错误,''' invalid literal for int() with base 10: '[(310, 71), (466, 145), (432, 285), (238, 289), (196, 150)]' '''

我用来读取和返回的代码是:

def function():
points = []
if (os.stat("file.txt").st_size!=0):
    print("Valid file found")
    with open('file.txt','r') as file:
        #points = []
        for line in file:
            points.append(line.strip())
else:
    print("No files found")

return points

如果文件是有效的,这将返回分数。并在脚本内部使用:

x = function()
pts = np.array([x],np.int32)

所以基本上 x 将包含值作为字符串,我需要将它们转换为与 int 相同的格式,以便我可以将其作为其他一些的输入。

任何有关这方面的帮助都将是有帮助和可观的。提前致谢。

【问题讨论】:

    标签: python python-3.x file


    【解决方案1】:

    欢迎使用 Stack Overflow,当您从 txt 文件或任何文件中读取 txt 时,文本以字符串格式存储。所以你必须做一些转换:

    import re
    def getList(text):
        someList = []
        text = re.sub(r"\s+", "", text, flags=re.UNICODE)
        for i in text[1:-2].split("),"):
            print(i)
            nums = i.split(",")
            print(nums)
            someList.append((int(nums[0][1:]),int(nums[1])))
        return someList
    

    将你打开的文件fn读取的文本传给this得到你要传给np.array([x],np.int32)fn的List

    【讨论】:

    • 谢谢绅士,在您的代码中再添加一些内容,我的 sn-p 工作,我将在下面添加这些行,x = getList(res) arr=[] for i in x: arr.append(i)
    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 2016-11-14
    • 2021-12-21
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    相关资源
    最近更新 更多