程序从文本文件中读取数据并以缩写形式显示输出,所有标点符号都输入到用户手中

时间:2015-11-25 00:03:15

标签: python

文本文件如下:textabbrv.txt

R:是

U:你

ttyl:稍后跟你说话

L8:晚

brb:马上回来

我尝试了很多来解决这个问题,但是有一个错误,我的程序是:

def main():

    indexEntries={}
    infile=open('textabbrv.txt','r')
    fields=extractRecord(infile)
    while len(fields)>0:
        set_entries(indexEntries,fields[1],fields[0])
        fields=extractRecord(infile)
    infile.close()
    printIndex(indexEntries)

def extractRecord(infile):

    line=infile.readline()
    if line!="":
        fields=line.split(":")
        page=fields[0].rstrip()
        term=fields[1].rstrip()
        return [page,term]
    else:
        return []

def set_entries(entries,term,page):


       pageSet=set([page])
       entries[term]=pageSet

def printIndex(entries):

    user_input=input("Enter a message to be translated: \n")


    if user_input!=" ":
        user_split=user_input.replace(","," ").replace("?"," ").replace("!"," ").\
                    replace(":"," ").replace(";"," ").split(" ")


    print()
    print("The translated text is: ")

    for long_form in entries:
        sentence=entries[long_form]

        for short_form in sentence:
            if short_form in user_split:
                print(user_input.replace(short_form,long_form))




main()

输出:

Enter a message to be translated: 
ttyl,brb

The translated text is: 

talk to you later,brb

ttyl,be right back

但是输出应该是这样的,应该只翻译成一行,我想我在for循环的某个地方搞砸了程序的结尾

Enter a message to be translated: 
ttyl,brb

The translated text is: 

talk to you later,be right back

1 个答案:

答案 0 :(得分:0)

首先,您看到的输出是由于:

print(user_input.replace(short_form,long_form))

每当您找到匹配项时,在原始用户输入中替换 匹配项,并将其打印出来,但您不会存储原始修改后的版本完全输入。

您可以通过执行以下操作来解决此问题:

user_input = user_input.replace(short_form,long_form)

然后在user_input的末尾打印新版printIndex。现在,这可能有问题,但这是另一个故事。

无论如何......你接近这个的方式有点不寻常。您正在以我期望的 reverse 方式填充indexEntries字典。你把索引作为值!代替:

1)我会导入csv并重写:

infile=open('textabbrv.txt','r')
fields=extractRecord(infile)
while len(fields)>0:
    set_entries(indexEntries,fields[1],fields[0])
    fields=extractRecord(infile)
infile.close()

为:

with open('textabbrv.txt','r') as infile:
    for (field1, field2) in csv.reader(infile, delimiter=':'):
        indexEntries[field1] = field2

在这个过程中我摆脱了extractRecordset_entries。现在字典看起来像{'brb': 'be right back', 'r': 'are, ...}

2)你正在拆分用户输入,但是你没有使用它。让我们改写一下:

for long_form in entries:
    sentence=entries[long_form]

    for short_form in sentence:
        if short_form in user_split:
            print(user_input.replace(short_form,long_form))

并成功:

output = []
for word in user_split:
    # The following could be written as
    # output.append(entries.get(word, word))
    if word in entries:
        output.append(entries[word])
    else:
        output.append(word)

print ','.join(output)