在python中,在复制和使用一行之后,向前推进n行

2024-03-29 00:43:31 发布

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

我在写剧本,看这里:

from pysnap import Snapchat
import time

usnlist = raw_input('Enter file name: ')

s = Snapchat()

def filter(username, password):
    s.login(username, password)
    with open (usnlist, 'r') as file:
        for line in file:
            ok = False
            while not ok:
                try:
                    resp = s.add_friend(line.rstrip("\n"))
                    if 'object' in resp.keys():
                        # 'object' is contained within resp as a key
                        if resp['object']['type']:
                            # type is 1
                            with open ('private.txt', 'a') as f: f.write(resp['object']['name']+"\n")
                            print line.rstrip("\n") + "'s",
                            print "privacy settings are set to: FRIENDS"
                        else:
                            # type is 0
                            with open ('n-private.txt', 'a') as f: f.write(resp['object']['name']+"\n")
                            print line.rstrip("\n") + "'s",
                            print "privacy settings are set to: EVERYONE"
                        s.delete_friend(line)
                    else:
                        # no object in resp, so it's an invalid username
                        print line.rstrip("\n") + " is not a valid username"
                    ok = True
                except:
                    time.sleep(5)
                    print "SNAPCHAT SERVER OVERLOAD - HOLD ON."

username = raw_input('Enter username: ')
password = raw_input('Enter password: ')

filter(username, password)

我现在想要的是能够输入一个值,我们称之为n 当我输入n时,bot只会刮取每一行n。你知道吗

例如。N = 2。 机器人现在只从列表中抓取和输入每秒钟一个用户名。你知道吗

我想到了一些东西,比如将[0::2]添加到:resp = s.add_friend(line.rstrip("\n")) 导致:resp = s.add_friend(line[0::2].rstrip("\n"))

但这不起作用,bot直接转到print "SNAPCHAT SERVER OVERLOAD - HOLD ON." 不查名字。你知道吗

我的想法是:

http://stackoverflow.com/questions/18155682/gathering-every-other-string-from-list-line-from-file

但所提供的信息还不足以让这一切顺利进行。 我使用python 2.7.8

我希望有一种方法可以告诉python:“获取文件中的每一行” 因为这基本上就是我要找的。你知道吗

太好了!你知道吗


Tags: fromfriendinputrawobjectisasline
2条回答

要获取文件中的每n行,请替换以下内容:

for line in file:

使用:

for line in file.read().splitlines()[0::n]:

你试过的是线,不是文件。文件没有切片支持,但是^{}模块有一个用于切片任意iterables的函数:

import itertools
for line in itertools.islice(file, None, None, n):
    do_whatever_with(line)

前两个参数是start和stop;这些参数的值None表示输入的开始和结束,因为不能像在常规切片中那样忽略它们。第三个论点是步骤。你知道吗

相关问题 更多 >