我有一个文件名为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'
为什么我会收到这个信息?我以为我做的是对的。正确的方法是什么?你知道吗
split
将字符串拆分为一个列表。当需要对每个单词调用实际列表时,您正在尝试对其执行rstrip
。你知道吗您可以循环浏览列表以实现以下目标:
或者,您也可以像已经这样拆分它&通过索引访问所需的单词。你知道吗
澄清:
在代码中,
split()
将word
转换为:您正在尝试对此执行一个
rstrip
,而不是单词本身。在列表中循环访问每个单词&;允许您使用rstrip
。你知道吗split()
函数返回一个不能对其执行string
函数的列表。 问题在于按顺序使用这两行在您的情况下,如果您确定这种格式,您可以这样做:
你的代码有一些问题。你知道吗
首先,一般来说,更喜欢使用
with
打开文件到open
。您不会关闭文件对象,因此在您关闭Python之前,操作系统认为它仍然处于打开状态(正在使用中)。你知道吗其次,
split
,当在字符串上运行时,将拆分为list
个字符串。您想从所有这样的子字符串中去掉逗号,因此需要遍历结果list
——在list
上运行strip
是没有意义的,因为它不是一个字符串。你知道吗最后,以这种方式遍历从文件中读取的文本并重新分配给
word
变量不会更改该文本,而只会更改word
变量所指向的内容,因此实际上不会看到任何效果。你知道吗示例:
原因是
i
连续指向从1到5的整数。当您对它执行+=
时,您所做的是更改i
指向的对象,而不是获取i
指向的对象并更改它。你知道吗打个比方:沿着路标到一所房子去修剪那里的草坪和移动路标指向另一所房子是有区别的。你知道吗
试试这个:
最后,请注意:纬度和经度是
float
,而不是int
,您可以根据需要进行相应的转换。你知道吗相关问题 更多 >
编程相关推荐