如何从文本文件中选择带元音的特定单词?

时间:2017-03-27 18:51:08

标签: python text-files

# Beginning project
import random

while True:
    g = random.randrange(0,1042)#verbs
    h = random.randrange(0,1435)#noun
    i = random.randrange(0,912) #adjective
    j = random.randrange(0,3)   #person
    k = random.randrange(0,2)   #what
    with open("verbs.txt","r") as z:
        verb = [x.strip().split(" ") for x in z.readlines()]
    with open("nouns.txt","r") as v:
        noun = [x.strip().split(" ") for x in v.readlines()]
    with open("adjectives.txt","r") as a:
        adject = [x.strip().split(" ") for x in a.readlines()]
    with open("person.txt","r") as b:
        who = [x.strip().split(" ") for x in b.readlines()]
    with open("what.txt","r") as c:
        what = [x.strip().split(" ") for x in c.readlines()]
file = open("written.txt","a")

output = (who[j] + verb[g] + what[k] + adject[i] + noun[h])
print(output)
file.write(str(output) + "\n")

到目前为止我的代码。 我有6个文本文件,每个都有单独的单词类型 例如,动词,形容词,名词,谁和什么以及最后一个被命名的内容都是它输出的地方。

我想做这样的事情: 如果在名词中找到元音则使用 或者如果在名词中找不到元音,则使用

但是在代码中 在python 2.7.12中

1 个答案:

答案 0 :(得分:0)

如果您不想使用spacy.io,可以使用以下逻辑。

nouns = ['ddd', 'ing', 'king']

for noun in nouns:
    output = 'so so'
    if any([letter in noun for letter in ['a', 'e', 'i', 'o', 'u']]):
        output += ' an ' + noun
    else:
        output += ' a ' + noun
    print output

但是,我猜,如果名词元音开头而不是中的,你可能想要 。如果是这种情况,您可以使用以下代码

for noun in nouns:
    output = 'so so'
    if any([noun.startswith(letter) for letter in ['a', 'e', 'i', 'o', 'u']]):
        output += ' an ' + noun
    else:
        output += ' a ' + noun
    print output