为什么我会收到一条属性消息



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

[纬度,经度]价值日期时间文本

文件中包含的数据的示例:

[41.29866962999999,-81.9153293300006] 6 2011-08-28 19:02:36工作需要飞过...我很高兴看到Spy Kids 4与我的生活...> [33.70290032999999,-117.95095704000001] 6 2011-08-28 19:03:13今天将是我一生中最伟大的一天。被雇用在我最好的朋友的Gparents 50周年纪念日拍照。60个老人。哇。
[38.80995493999997,-77.125144050000003] 6 2011-08-28 19:07:05我只是把我的生活放在5个手提箱中

我的分配要求我提取每行的第一和第二个索引(纬度和经度,是整数)。问题是这些字符具有诸如" [",","]之类的字符,我想删除这些字符。

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'对象没有属性'rstip'

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

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

split将字符串分配到列表中。当您需要在每个单词上调用它时,您正在尝试在实际列表上执行rstrip

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

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

另外,您可以像已经做到的那样拆分它。通过索引访问您想要的单词。

进行澄清:

在您的代码中,split()word变成:

[" [38.80995493999997,'',

" -77.1251440500003]&quot

" 6",

2011-08-28 19:07:05&quot,

; i&quot,

just',

" put",

" my&quot",

"生命",

;

"喜欢",

5&quot,

"手提箱"

您正在尝试对此执行一个rstrip,而不是单词本身。遍历列表访问每个单词&允许您使用rstrip

您的代码有一些错误。

首先,首先,更喜欢使用with将文件打开至open。您不会关闭文件对象,因此OS认为它仍然打开(在使用中),直到您关闭Python。

第二,split,当在字符串上运行时, splits 将其插入字符串的list中。您想从所有此类子字符串中剥离逗号,因此您需要迭代所得list-在list上运行strip是没有意义的,因为它不是字符串。

最后,以这种方式从文件中读取的文本进行迭代,并将其重新分配到word变量不会更改该文本的入门,而只会更改word变量点的点,因此您实际上不会看到任何效果。p>示例:

>>> 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,您可以在必要时相应地转换它们。

相关内容

最新更新