为什么我会收到一条AttributeError消息?

2024-09-27 07:30:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个文件名为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(",") 

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

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

为什么我会收到这个信息?我以为我做的是对的。正确的方法是什么?你知道吗


Tags: 文件oftointxt文件名myline
3条回答

split将字符串拆分为一个列表。当需要对每个单词调用实际列表时,您正在尝试对其执行rstrip。你知道吗

您可以循环浏览列表以实现以下目标:

for line in infile:  
    line=line.rstrip()  
    for word in line.split():
        word=word.rstrip(",")

或者,您也可以像已经这样拆分它&通过索引访问所需的单词。你知道吗

澄清:

在代码中,split()word转换为:

["[38.809954939999997,",

"-77.125144050000003]",

"6",

"2011-08-28 19:07:05",

"I",

"just",

"put",

"my",

"life",

"in",

"like",

"5",

"suitcases"]

您正在尝试对此执行一个rstrip,而不是单词本身。在列表中循环访问每个单词&;允许您使用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

你的代码有一些问题。你知道吗

首先,一般来说,更喜欢使用with打开文件到open。您不会关闭文件对象,因此在您关闭Python之前,操作系统认为它仍然处于打开状态(正在使用中)。你知道吗

其次,split,当在字符串上运行时,拆分为list个字符串。您想从所有这样的子字符串中去掉逗号,因此需要遍历结果list——在list上运行strip是没有意义的,因为它不是一个字符串。你知道吗

最后,以这种方式遍历从文件中读取的文本并重新分配给word变量不会更改该文本,而只会更改word变量所指向的内容,因此实际上不会看到任何效果。你知道吗

示例:

>>> numbers = [1, 2, 3, 4, 5]
>>> for i in numbers:
...     i += 1
...
>>> numbers
[1, 2, 3, 4, 5]

原因是i连续指向从1到5的整数。当您对它执行+=时,您所做的是更改i指向的对象,而不是获取i指向的对象并更改它。你知道吗

打个比方:沿着路标到一所房子去修剪那里的草坪和移动路标指向另一所房子是有区别的。你知道吗

试试这个:

tweet_path = input("Enter name of tweet file: ")
with open(tweet_path, "r", encoding='utf-8') as f:
    coordinates = [line.split()[:2] for line in f]

cleaned_coordinates = [(lat[1:-1], lon) for lat, lon in coordinates]

最后,请注意:纬度和经度是float,而不是int,您可以根据需要进行相应的转换。你知道吗

相关问题 更多 >

    热门问题