在python中循环替换函数以获得不同的随机输出

时间:2017-02-04 04:26:20

标签: python

嘿,如果我不能有效地表达我的问题,我会事先提前通知,但我正处于需要帮助的地步。

基本上我想浏览一个文本列表,并用随机选择的单词替换某些元素。我可以从列表中随机拉出单词,但是一旦我将它们分配给某个单词,它们就会完全相同。

I.E我想改变这个:

DT JJ NNP  DT JJ NN I PRP VBD JJ NN IN DT JJ NN CC VBD VBN IN RB CD 8 CD JJ
NN IN I PRP VBP IN PRP JJ NN  PRP VBP RP DT JJ NN CC I PRP VBD VBG RB RB  VB
DT NN VBD VBG RB
IN DT JJ NN CC PRP VBD VBN IN NN CC WP I PRP VBP TO VB NN

到此:

  DT JJ NNP  DT JJ shopping I PRP VBD JJ bag IN DT JJ house CC VBD VBN IN RB CD 8 CD JJ fun 
 IN I PRP VBP IN PRP JJ hatred  PRP VBP RP DT JJ bum CC I PRP VBD VBG RB RB CC VB DT 
到目前为止,我的代码是:

import random, re

def get_noun():
    infile = open('nouns.txt', 'r') #opens the file, preps it to be read
    nouns = infile.readlines() # reads each line of the file
    infile.close() # closes the file


    index = 0 # starts at the begining of the list

    while index < len(nouns): # first part of the counter
        nouns[index] = nouns[index].rstrip('\n') # i believe this goes through and strips each line of the /n thing, which is usually output at the end of each line
        index += 1 # counts up until it hits the final length number of the list
    noun = random.choice(nouns) # outputs a random line from the list.
    return noun

print (get_noun() + get_noun())



def work_plz():
    fun = open('struc1.txt', 'r')
    readS = fun.readlines()
    fun.close

    index = 0

    while index < len(readS): # first part of the counter
        readS[index] = readS[index].rstrip('\n') # i believe this goes through and strips each line of the /n thing, which is usually output at the end of each line
        index += 1
    okay = [w.replace('NN', get_noun()) for w in readS]
    return okay

print (work_plz() + work_plz())

我得到的输出是:

DT JJ shopping P DT JJ shopping I PRP VBD JJ shopping IN DT JJ
shopping  CC    VBD VBN IN RB CD 8 CD JJ shopping IN I PRP VBP IN PRP JJ   
shopping  

在程序中,我想用get_noun()函数中的不同单词替换所有NN,但它似乎只将一个NN拉入缓冲区并将其用于所有NN。

任何人都知道我哪里出错了?我怀疑这与某事有关:

 okay = [w.replace('NN', get_noun()) for w in readS]

但我不知道如何重新循环它以为每个'NN'产生不同的结果。

如果你可以帮助我,我会非常高兴!!!!

欢呼声。

ELlliot

编辑:

这是我从thanasissdr复制的代码:

 import random

nouns = 'file/path/nouns.txt'
infile = file/path/struc1.txt'

def get_noun(file):
''' This function takes as input the filepath of the file where the words you want to replace with are stored and it returns
a random word of this list. We assume that each word is stored in a new line.'''
def random_choice(lista):
    return random.choice(lista)
with open(file, 'r') as f:
    data  = f.readlines()
    return random.choice(data).rstrip()


with open(infile, 'r') as f:

big = [] ## We are going to store in this list all the words in the "infile" file.
data = f.readlines() ## Read the file.
for row in data:
    c = row.rstrip() ## Remove all the '\n' characters.'
    d = ','.join(c.split())  ## Separate all the words with comma.
    d = d.split(',') ## Storing all the words as separate strings in a list.

    ## This is the part where we replace the words that meet our criteria.
    for j in range(len(d)):
        if d[j]== 'NN':
            d[j] = get_noun(nouns)
    big.extend(d) ## join all the rows (lists) in a big list.
print (' '.join(big)) ## returns the desired output.

这是活着的。非常感谢你们所有人的帮助。我得到了这个工作,作为脚本小子我是我将保持它像这哈哈哈。我会尽力去理解你们给我的所有东西,但是我很满意这样做。我希望这不是很差的礼仪!所有传说!

2 个答案:

答案 0 :(得分:0)

我不知道你是否了解字典,但鉴于你似乎正在使用nltk或类似的东西,我会假设是的。这是一个维护名为Words[code]的字典的版本,其中代码类似于'NN'。每个条目都是一个单词列表,因此您可以随机选择一个。

您可以读取多个文件,每个代码等。我正在使用一些虚拟数据编写文件 - 您应该在尝试使用它之前将其删除。

import random

with open('nouns.txt', 'w') as outfile:
    contents = """
fox dog
shopping bag # Not sure this is right. Shopping?
fun house
hatred # Or this
bum
"""
    print(contents, file=outfile)

with open('struc1.txt', 'w') as outfile:
    contents = """
DT JJ NNP  DT JJ NN I PRP VBD JJ NN IN DT JJ NN CC VBD VBN IN RB CD 8 CD JJ
NN IN I PRP VBP IN PRP JJ NN  PRP VBP RP DT JJ NN CC I PRP VBD VBG RB RB  VB
DT NN VBD VBG RB
IN DT JJ NN CC PRP VBD VBN IN NN CC WP I PRP VBP TO VB NN
"""
    print(contents, file=outfile)

Words = dict()

def get_words(path, code):

    words = Words[code] = []

    with open(path, 'r') as infile:
        for line in infile:
            words.extend(line.split('#', 1)[0].strip().split())

def random_word(code):
    wordlist = Words.get(code)
    if wordlist is None:
        return code

    return random.choice(wordlist)


def work_plz(path):
    with open(path, 'r') as infile:
        for line in infile:
            line_out = []
            for token in line.strip().split():
                line_out.append(random_word(token))

            print(' '.join(line_out))

get_words('nouns.txt', 'NN')
work_plz('struc1.txt')

答案 1 :(得分:0)

如果您感兴趣我创建了一个完全符合您要求的代码(python 3)。

import random

nouns = '/path/to/file/containing/the/nouns.txt'
infile = '/path/to/initial/file.txt'

def get_noun(file):
    ''' This function takes as input the filepath of the file where the words you want to replace with are stored and it returns
    a random word of this list. We assume that each word is stored in a new line.''' 
    def random_choice(lista):
        return random.choice(lista)
    with open(file, 'r') as f:
        data = f.readlines()
        return random.choice(data).rstrip()


with open(infile, 'r') as f:

    big = [] ## We are going to store in this list all the words in the "infile" file (after our desired modifications).
    data = f.readlines() ## Read the initial file.
    for row in data:
        c = row.rstrip() ## Remove all the '\n' characters.
        d = ','.join(c.split()) ## Separate all the words with comma. 
        d = d.split(',') ## Storing all the words as separate strings in a list.

        ## This is the part where we replace the words that meet our criteria.
        for j in range(len(d)):
            if d[j] == 'NN':
                d[j] = get_noun(nouns)
        big.extend(d) ## Joins all the rows (lists) in the 'big' list.
    print (' '.join(big)) ## Prints out the desired output.