从python脚本中生成的文本中删除重复的单词

kul*_*tur 4 python string text duplicates

我制作了一个python脚本来从输入文件中获取文本,并根据切割技术(http://en.wikipedia.org/wiki/Cut-up_technique)随机重新排列创意写作项目的单词.

这是目前的脚本.注意:我正在运行这个作为服务器端包括.

#!/usr/bin/python
from random import shuffle 

src = open("input.txt", "r")
srcText = src.read()
src.close()

srcList = srcText.split()
shuffle(srcList)
cutUpText = " ".join(srcList)
print("Content-type: text/html\n\n" + cutUpText)
Run Code Online (Sandbox Code Playgroud)

这基本上完成了我希望它做的工作,但我想做的一个改进是识别输出中的重复单词并删除它们.为了澄清,我只想识别序列中的重复项,例如"the the"或"II I".我不想这样做,例如,"the"只在整个输出中出现一次.

有人能指出我正确的方向来开始解决这个问题吗?(我的背景不是编程,所以我基本上通过python手册的大量阅读和浏览这个网站把这个脚本放在一起.请对我温柔.)

Ned*_*der 5

你可以编写一个生成器来生成没有重复的单词:

def nodups(s):
    last = None
    for w in s:
        if w == last:
            continue
        yield w
        last = w
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的程序中使用它:

cutUpText = " ".join(nodups(srcList))
Run Code Online (Sandbox Code Playgroud)