Tôi chưa quen với Python và những gì tôi đang cố gắng làm là thay thế văn bản/chuỗi trong tệp JSON, từ lệnh shell os python. Tôi có phần nhận được kết quả mà tôi đang tìm kiếm, nhưng nó đang nối thêm khoảng trắng/tạo một dòng mới trong tệp JSON. Đây về cơ bản là những gì tôi đang cố gắng thực hiện:
- Tôi có một tệp JSON tĩnh [add.json]
- Tôi đang chạy hai lệnh os shell trong Python và lưu trữ đầu ra đó vào các tệp văn bản riêng biệt.
- Sau đó tôi muốn lấy các giá trị trong hai tệp TXT đó và thay thế hai chuỗi trong tệp JSON.
Dưới đây là những gì tôi hiện có [để làm cho nó đơn giản, tôi đã thay thế các lệnh AWS CLI thực sự bằng các lệnh đơn giản]
import os
import fileinput
cmd = 'hostname > host.txt'
cmd2 = 'echo mama > echo.txt'
os.system[cmd]
os.system[cmd2]
file = open['host.txt']
contents = file.read[]
with open["out.json", "wt"] as fout:
with open["add.json", "rt"] as fin:
for line in fin:
fout.write[line.replace['dns',contents]]
file2 = open['echo.txt']
contents2 = file2.read[]
with open["out2.json", "wt"] as fout2:
with open["out.json", "rt"] as fin2:
for line in fin2:
fout2.write[line.replace['ip', contents2]]
Và đây là kết quả mà nó mang lại:
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
Như bạn có thể thấy, sau tên và giá trị, nó thực sự thay thế các giá trị, nhưng thêm một dòng mới và tạo ra JSON không hợp lệ.
Đây là tệp tôi thay thế các giá trị trong:
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
Cảm ơn bạn trước cho bất kỳ câu trả lời. Tôi biết những gì tôi có ở trên là rất bẩn, và tôi chắc chắn rằng phải có một cách tốt hơn/sạch hơn để hoàn thành những gì tôi đang cố gắng làm, nhưng cuối cùng tôi biết tất cả chúng ta phải bắt đầu ở đâu đó và tôi thậm chí không thể bắt đầu Để giải thích tôi biết ơn như thế nào với cộng đồng này vì tất cả sự giúp đỡ mà nó được cung cấp cho đến nay.
Vì vậy, đây là JSON:
{
"template_name": "template1",
"ch2": {
"textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
"bigskip": "My first cookbook"
}
}
Và khi tôi cố gắng truy cập nó với mã này:
directory = str[uuid.uuid4[]]
parent_dir = "C:\PycharmProjects\pythonProject"
src = "C:\PycharmProjects\pythonProject\Template"
path = os.path.join[parent_dir, directory]
destination = shutil.copytree[src, directory]
with open["C:\PycharmProjects\pythonProject\\test.json"] as f:
data = json.load[f]
with open[f"C:\PycharmProjects\pythonProject\\Template\\body\ch2.tex", 'r']as f:
text = f.read[]
for key, value in data.items[]:
text = text.replace['{'+key+'}', value]
with open[f"C:\PycharmProjects\pythonProject\\{destination}\\body\ch2.tex", "w"]as out:
out.write[text]
Nó trả về lỗi sau:
Traceback [cuộc gọi gần đây nhất cuối cùng]:
Tệp "uuid-test.py", dòng 21, trong
text = text.replace ['{'+key+'}', value]
TypeError: thay thế [] đối số 2 phải là str, không phải dict
Nếu có ai có thể giúp tôi sẽ rất biết ơn
Cảm ơn bạn trước!
Sau đây là 30 ví dụ mã của String.replace []. Bạn có thể bỏ phiếu cho những người bạn thích hoặc bỏ phiếu cho những người bạn không thích và đi đến dự án gốc hoặc tệp nguồn bằng cách theo các liên kết trên mỗi ví dụ. Bạn cũng có thể muốn kiểm tra tất cả các chức năng/lớp có sẵn của chuỗi mô -đun hoặc thử chức năng tìm kiếm.30 code examples of string.replace[]. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module string, or try the search function
Ví dụ 1
def getIndex[form, pos='noun']: """Search for _form_ in the index file corresponding to _pos_. getIndex applies to _form_ an algorithm that replaces underscores with hyphens, hyphens with underscores, removes hyphens and underscores, and removes periods in an attempt to find a form of the string that is an exact match for an entry in the index file corresponding to _pos_. getWord[] is called on each transformed string until a match is found or all the different strings have been tried. It returns a Word or None.""" def trySubstitutions[trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor[pos]]: if lookup and dictionary.has_key[form]: return dictionary[form] elif substitutions: [old, new] = substitutions[0] substitute = string.replace[form, old, new] and substitute != form if substitute and dictionary.has_key[substitute]: return dictionary[substitute] return trySubstitutions[trySubstitutions, form, substitutions[1:], lookup=0] or \ [substitute and trySubstitutions[trySubstitutions, substitute, substitutions[1:]]] return trySubstitutions[returnMatch, form, GET_INDEX_SUBSTITUTIONS]
Ví dụ #2
def __getitem__[self, index]: """If index is a String, return the Word whose form is index. If index is an integer n, return the Word indexed by the n'th Word in the Index file. >>> N['dog'] dog[n.] >>> N[0] 'hood[n.] """ if isinstance[index, StringType]: return self.getWord[index] elif isinstance[index, IntType]: line = self.indexFile[index] return self.getWord[string.replace[line[:string.find[line, ' ']], '_', ' '], line] else: raise TypeError, "%s is not a String or Int" % `index` # # Dictionary protocol # # a Dictionary's values are its words, keyed by their form #
Ví dụ #3
def getIndex[form, pos='noun']: """Search for _form_ in the index file corresponding to _pos_. getIndex applies to _form_ an algorithm that replaces underscores with hyphens, hyphens with underscores, removes hyphens and underscores, and removes periods in an attempt to find a form of the string that is an exact match for an entry in the index file corresponding to _pos_. getWord[] is called on each transformed string until a match is found or all the different strings have been tried. It returns a Word or None.""" def trySubstitutions[trySubstitutions, form, substitutions, lookup=1, dictionary=dictionaryFor[pos]]: if lookup and dictionary.has_key[form]: return dictionary[form] elif substitutions: [old, new] = substitutions[0] substitute = string.replace[form, old, new] and substitute != form if substitute and dictionary.has_key[substitute]: return dictionary[substitute] return trySubstitutions[trySubstitutions, form, substitutions[1:], lookup=0] or \ [substitute and trySubstitutions[trySubstitutions, substitute, substitutions[1:]]] return trySubstitutions[returnMatch, form, GET_INDEX_SUBSTITUTIONS]
Ví dụ #4
def __getitem__[self, index]: """If index is a String, return the Word whose form is index. If index is an integer n, return the Word indexed by the n'th Word in the Index file. >>> N['dog'] dog[n.] >>> N[0] 'hood[n.] """ if isinstance[index, StringType]: return self.getWord[index] elif isinstance[index, IntType]: line = self.indexFile[index] return self.getWord[string.replace[line[:string.find[line, ' ']], '_', ' '], line] else: raise TypeError, "%s is not a String or Int" % `index` # # Dictionary protocol # # a Dictionary's values are its words, keyed by their form #
Ví dụ #5
def main[]: print "This program converts a textual message into a sequence" print "of numbers representing the ASCII encoding of the message." print # Get the message to encode message = raw_input["Please enter the message to encode: "] n = int[raw_input["Enter the key value"]] print print "Here are the ASCII codes:" z = string.replace[message,"z","a"] z1 = string.replace[z,"Z","A"] # Loop through the message and print out the ASCII values for ch in z1: a = chr[ord[ch] + n], # use comma to print all on one line. print " ".join[a], print
Ví dụ #6
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
0Ví dụ #7
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
1Ví dụ #8
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
2Ví dụ #9
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
3Ví dụ #10
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
4Ví dụ #11
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
5Ví dụ #12
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
6Ví dụ #13
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
7Ví dụ #14
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
8Ví dụ #15
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
9Ví dụ #16
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
0Ví dụ #17
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
1Ví dụ #18
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
2Ví dụ #19
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
3Ví dụ #20
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
4Ví dụ #21
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
5Ví dụ #22
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
8Ví dụ #23
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
9Ví dụ #24
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
0Ví dụ #25
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
1Ví dụ #26
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
2Ví dụ #27
{
"template_name": "template1",
"ch2": {
"textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
"bigskip": "My first cookbook"
}
}
1Ví dụ #28
{
"template_name": "template1",
"ch2": {
"textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
"bigskip": "My first cookbook"
}
}
2Ví dụ #29
{
"template_name": "template1",
"ch2": {
"textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
"bigskip": "My first cookbook"
}
}
3Ví dụ #30
{
"template_name": "template1",
"ch2": {
"textbf": "Many novice writers tend to make a sharp distinction between content and style, thinking that a paper can be strong in one and weak in the other, but focusing on organization shows how content and style converge in deliberative academic writing.",
"bigskip": "My first cookbook"
}
}
1