簡體   English   中英

在python中為不同的隨機輸出循環替換功能

[英]Looping a replace function in python for different random outputs

嘿,如果我不能很好地闡明我的問題,我會提前向我表示歉意,但是我現在需要幫助。

基本上,我想瀏覽文本列表,並用隨機選擇的單詞替換某些元素。 我可以從列表中隨機抽取單詞,但是一旦將它們分配給特定單詞,它們都是一樣的。

IE瀏覽器,我想改變這個:

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,但似乎只將其中之一拉入緩沖區並將其用於所有緩沖區。

有人知道我要去哪里錯嗎? 我懷疑這與以下內容有關:

 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.

它還活着。 非常感謝你們的所有幫助。 我讓這個工作,作為腳本小子,我要保持這種哈哈哈。 我會盡力了解你們向我展示的所有內容,但是我對讓它照這樣運行感到滿意。 我希望這不是可憐的禮節! 所有傳說!

我不知道您是否對字典有所了解,但是鑒於您似乎正在使用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')

如果您有興趣,我創建了一個代碼,該代碼可以完全滿足您的要求( 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.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM