简体   繁体   English

在python中打印为字典

[英]Printing as a dictionary in python

I have a problem in python.我在python中有问题。 I want to create a function to print a file from user to a new file (example.txt).我想创建一个函数来将文件从用户打印到新文件 (example.txt)。

The old file is like this:旧文件是这样的:

{'a':1,'b':2...)

and I want the new file like:我想要这样的新文件:

a   1,b   2(the next line)

But the function which I made can run but it doesn't show anything in the new file.但是我创建的函数可以运行,但在新文件中没有显示任何内容。 Can someone help me please.有人能帮助我吗。

def printing(file):
    infile=open(file,'r')
    outfile=open('example.txt','w')

    dict={}
    file=dict.values()
    for key,values in file:
        print key
        print values
    outfile.write(str(dict))
    infile.close()
    outfile.close()

This creates a new empty dictionary:这将创建一个新的空字典:

dict={}

dict is not a good name for a variable as it shadows the built-in type dict and could be confusing. dict不是变量的好名字,因为它掩盖了内置类型dict并且可能会造成混淆。

This makes the name file point at the values in the dictionary:这使得名称file指向字典中的值:

file=dict.values()

file will be empty because dict was empty. file将是空的,因为dict是空的。

This iterates over pairs of values in file .这将迭代file的值对。

for key,values in file:

As file is empty nothing will happen.由于file为空,什么都不会发生。 However if file weren't empty, the values in it would have to be pairs of values to unpack them into key , values .但是,如果file不为空,则其中的值必须是成对的值才能将它们解包为key , values

This converts dict to a string and writes it to the outfile :这将dict转换为字符串并将其写入outfile

outfile.write(str(dict))

Calling write with a non-str object will call str on it anway, so you could just say:使用non-str对象调用write将对其调用str ,因此您可以说:

outfile.write(dict)

You don't actually do anything with infile .你实际上没有对infile做任何事情。

You can use re module (regular expression) to achieve what you need.您可以使用 re 模块(正则表达式)来实现您的需求。 Solution could be like that.解决方案可能是这样的。 Of course you can customize to fit your need.当然,您可以自定义以满足您的需要。 Hope this helps.希望这可以帮助。

import re
def printing(file):
   outfile=open('example.txt','a')
   with open(file,'r') as f:
       for line in f:
           new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', line)
           outfile.write(new_string)

printing('output.txt')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM