从Python中的文本文件中获取某些单词和短语

时间:2013-04-14 14:54:17

标签: python string list for-loop

我有这个代码块,它通过一个文本文件,逐行抓取它并将其分成单独的单词。这一切都很好,但在我的文本文件中,我有一些以' - '开头并以' - '结尾的单词和短语,例如'-foo-'或'-foo bar-'。现在,由于代码分为'-foo'和'bar-',它们被拆分了。我理解为什么会发生这种情况。

我的计划是抓住那些以' - '开头和结尾的实例,将它们存储到一个单独的列表中,然后用户将每个短语更改为新的,将它们放回列表中。如果它是两个单独的单词,我如何告诉它抓取某个短语?

def madLibIt(text_file):
    listOfWords = [] #creates a word list
    for eachLine in text_file: #go through eachLine, and split it into 
        #seperate words
        listOfWords.extend(eachLine.split())
 print listOfWords

2 个答案:

答案 0 :(得分:2)

在没有分隔符的情况下调用str.split()会按空格分割文本,因此您不会将-用作分隔符。

您可以re.findall()使用模式(-.+?-)

matches = re.findall(r'(-.+?-)', 'This is a -string- with a -foo bar-')
print(matches) # ['-string-', '-foo bar-']

答案 1 :(得分:1)

这个正则表达式完全抓住你想要的东西。

import re

s = 'This is a string with -parts like this- and -normal- parts -as well-'

print re.findall(r'((?:-\w[\w\s]*\w-)|(?:\b\w+\b))', s)

>>> 
['This', 'is', 'a', 'string', 'with', '-parts like this-', 'and', '-normal-', 'parts', '-as well-']
相关问题