gpt4 book ai didi

python - 为什么我会收到 AttributeError 消息?

转载 作者:行者123 更新时间:2023-11-28 18:58:39 26 4
gpt4 key购买 nike

我有一个名为 tweets.txt 的文件。每行的格式为:

[latitude, longitude] value date time text

文件中包含的数据示例:

[41.298669629999999, -81.915329330000006] 6 2011-08-28 19:02:36 Work needs to fly by ... I'm so excited to see Spy Kids 4 with then love of my life ... ARREIC
[33.702900329999999, -117.95095704000001] 6 2011-08-28 19:03:13 Today is going to be the greatest day of my life. Hired to take pictures at my best friend's gparents 50th anniversary. 60 old people. Woo.
[38.809954939999997, -77.125144050000003] 6 2011-08-28 19:07:05 I just put my life in like 5 suitcases

我的作业要求我提取每行的第一个和第二个索引(纬度和经度,它们是整数)。问题是它们有诸如“[”、“、”和“]”之类的字符,我想删除它们。

tweetfile=input("Enter name of tweet file: ")  
infile=open(tweetfile,"r",encoding="utf-8")
for line in infile:
line=line.rstrip()
word=line.split()
word=word.rstrip(",")

如您所见,每当我在上面的字条行中输入参数时,无论是 [、逗号还是 [,我都会收到一条错误消息:

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

为什么我会收到这条消息?我以为我在做正确的事。这样做的正确方法是什么?

最佳答案

split() 函数返回一个您不能对其执行string 函数的列表。问题在于按顺序使用这两行

word=line.split()  #this will actually return a list of words not just a word
word=word.rstrip(",")

在你的情况下,如果你确定这个确切的格式,你可以这样做:

tweetfile=input("Enter name of tweet file: ")  
infile=open(tweetfile,"r",encoding="utf-8")
for line in infile:
line=line.rstrip()
coordinates_string=line.split(']')
coordinates_cleaned = coordinates_string[1:] #removes the [
lat_lon_string = coordinates_cleaned.split(',') #split lat lon
lat = lat_lon_string[0].strip()
lon = lat_lon_string[1].strip()
# convert to float if you would like then after

关于python - 为什么我会收到 AttributeError 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55271199/

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