Python排除空lin

2024-09-27 07:33:22 发布

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

这是我的Twitter机器人的一个代码,它通过文本文件向Twitter发送特定的行。 以下代码段用于检查该行是空行还是包含内容的行:

...

for line in buff[:]:
        if len(line)<=140 and len(line)>0:
            print ("Tweeting...")
            twitter.update_status(status=line)
            time.sleep(3)
            with open ('liners.txt', 'w') as tweetfile:
                buff.remove(line)
                tweetfile.writelines(buff)
        elif len(line)=0:
            with open ('liners.txt', 'w') as tweetfile:
                buff.remove(line)
                tweetfile.writelines(buff)
            print("Skipped line - Empty line detected")
            continue
        else:
            with open ('liners.txt', 'w') as tweetfile:
                buff.remove(line)
                tweetfile.writelines(buff)
            print ("Skipped line - Char length violation")
            continue 

...

文本文件在每行之间包含换行符,我想知道为什么if块变成了换行符的true。这里的条件语句有什么问题?你知道吗

你知道吗衬里.txt:(第一行是换行)


The dyslexic devil worshipper sold his soul to Santa.

You kill vegetarian vampires with a steak to the heart.

There was a prison break and I saw a midget climb up the fence. As he jumped down he sneered at me and I thought, well that’s a little condescending.


Tags: andtxtwritelineslenaswithlinetwitter
1条回答
网友
1楼 · 发布于 2024-09-27 07:33:22

在测试行长度时,换行符仍被视为字符。在检查它的长度之前,你得先把它剥掉。从

if len(line)<=140 and len(line)>0:

收件人:

line = line.strip(r'\n')
if len(line)<=140 and len(line)>0:

事实上,你可以采取额外的步骤只是真理测试线。剥离换行符后,无需测试长度>;0:

line = line.strip(r'\n')
if line and len(line) <= 140:
...

相关问题 更多 >

    热门问题