2014-05-10 37 views
0

我正在学习Python,并且作为一个学习项目,我正在开发一个twitter bot。我正在使用Python 3.我使用以下几行来发送推文。删除和更新文本文件中的行 - Python

什么是李小龙最喜欢的饮料? Wataaaaah!
诵读困难的恶魔崇拜者将他的灵魂卖给了圣诞老人。
你用牛排杀死心脏素食吸血鬼。
有一次监狱休息时间,我看到一只侏儒爬上围栏。当他跳下来时,他嘲笑我,我想,这有点居高临下。

这是我的代码,使用Twython鸣叫:

from twython import Twython, TwythonError 
import time 

APP_KEY = '##########' # Customer Key here 
APP_SECRET = '#############' # Customer secret here 
OAUTH_TOKEN = '###############' # Access Token here 
OAUTH_TOKEN_SECRET = '################' # Access Token Secret here 

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) 

try: 
    with open('jokes.txt', 'r+') as file: 
     buff = file.readlines() 

    for line in buff: 
     if len(line)<140: 
      print ("Tweeting...") 
      twitter.update_status(status=line) 
      time.sleep(3) 
      with open ('jokes.txt', 'r+') as file: 
       buff.remove(line) 
       file.writelines(buff) 
     else: 
      with open ('jokes.txt', 'r+') as file: 
       buff.remove(line) 
       file.writelines(buff) 
      print ("Skipped line - Char Length Violation") 
      continue 


except TwythonError as e: 
    print (e) 

我想跳过这个拥有超过140个字符与控制台Skipped line - Char Length Violation在消息上线,然后删除特定的行和更新文件。该脚本通过忽略该行成功鸣叫,但无法打印控制台消息。它也无法从文本文件中删除该行。

我不知道为什么第三行You kill vegetarian vampires with a steak to the heart.被跳过。

我运行该脚本后,这有什么错我的代码,为什么我的文本文件看起来像这样:

的诵读困难的魔鬼崇拜者,出卖了自己的灵魂圣诞老人。
有一次监狱休息时间,我看到一只侏儒爬上围栏。当他跳下 他嘲笑我,我想,这是一个有点居高临下。 在我身上,我想,这是一个有点居高临下。我认为, 以及有点居高临下。

回答

0

首先,尽量避免使用file来命名变量,因为它是Python中用于file类型的保留关键字。

固定代码:

from twython import Twython, TwythonError 
import time 

APP_KEY = '##########' # Customer Key here 
APP_SECRET = '#############' # Customer secret here 
OAUTH_TOKEN = '###############' # Access Token here 
OAUTH_TOKEN_SECRET = '################' # Access Token Secret here 

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) 

try: 
    with open('jokes.txt', 'r+') as fp: 
     buff = fp.readlines() 

    for line in buff[:]: 
     if len(line) < 140: 
      print("Tweeting...") 
      twitter.update_status(status=line) 
      time.sleep(3) 
      with open('jokes.txt', 'w') as fp: 
       buff.remove(line) 
       fp.writelines(buff) 
     else: 
      with open('jokes.txt', 'w') as fp: 
       buff.remove(line) 
       fp.writelines(buff) 
      print("Skipped line - Char Length Violation") 
      continue 


except TwythonError as e: 
    print(e) 

一般 - 像在这种情况下 - 这不是修改迭代(列表)一个周期内一个好主意,在同一个迭代其迭代。这里的诀窍是for line in buff[:]:行中的切片运算符,它将复制buff列表,并在副本上迭代而不是在原始buff列表中进行迭代。另外,当你想覆盖文件时,你必须以'w'模式打开它,而不是'r +'模式,因为'r +'不会首先截断你的文件。

0
file.close() 

似乎是with ... as file:块下错位。 with的优点是你不需要做这个簿记。

elsefile对象已关闭,所以file.writelines()应引发异常。

据我所见,buff是一个字符串,因此是不可变的。您可能想尝试buff = buff.remove(...),但它是否有remove方法?

+0

谢谢。我编辑了代码。 –

+0

修正了'else'块... –