循环和替换后,最后一个空格仍保留在数据中

时间:2015-04-10 22:54:00

标签: python replace whitespace

我遇到了一个令人难以置信的问题,我试图删除数据 keyword.txt 的所有空格并仅保留字母串。但是在循环并将每个空格替换为空字段后,仍会在输出中看到一个新行,因此会弄乱另一个输出。

我不知道该怎么做。

脚本:

#!/usr/bin/python

kf = open ('keyword.txt', 'r')
sl = open ('syslog.txt', 'r')

keywordList = []

for keyword in kf:
    keyword = keyword.replace('\n', "")
    keywordList.append(keyword)
    print keyword

for string in sl:
    for keyword in keywordList:
        if keyword in string:
            print "**"+keyword+"**"

这产生的输出样本:

**anacron**
****
**anacron**
****
**CRON**
****

您可以看到****出现在行中,因为它将空格标识为关键字。这就是问题......

keyword.txt

NetworkManager
avahi-daemon
dnsmasq
dbus
kernel
dhclient
CRON
bluetoothd
failsafe
modem-manager
udev-configure-printer
modem-manager
polkitd
anacron
acpid
rt-kit daemon
goa
AptDaemon
AptDaemon.PackageKit
AptDaemon.Worker
python

2 个答案:

答案 0 :(得分:2)

似乎空格不是作为每个单词的一部分被抓取而是作为单个单词。

尝试阅读像这样的文件

kf = [x.strip() for x in open('keyword.txt', 'r') if not x.strip() == '']

然后像你一样遍历列表。

其他变体包括

kf = [x.strip() for x in open('keyword.txt', 'r') if x.strip() != '']

kf = [x.strip() for x in open('keyword.txt', 'r') if x.strip()]

如评论中所述

答案 1 :(得分:0)

您的KeywordList可能包含重复的关键字。请尝试使用set代替:

keywords = set()

for keyword in kf:
    keyword = keyword.replace('\n', "")
    keywords.add(keyword)
    print keyword

for string in sl:
    for keyword in keywords:
        if keyword in string:
            print "**"+keyword+"**"

我用这些数据尝试了它并且它有效...

kf = ['anacron\n','anacron\n','CRON\n']
sl = ['a sentence with anacron\n','another sentence\n', 'one more\n', 'anacron\n','finally\n','one with CRON\n']