简体   繁体   中英

How convert a list of strings to a single delimited string?

I've been looking through dozens of threads and can't find an answer to this, but hopefully it's not too difficult. I need to take a list of strings and convert them to a single string comma delimited. Also need that single string to be held by a variable.

I'm using this script to call keyword tags from an API.

import requests, csv

api_key = 'abc'
api_secret = 'xyz'
image_url = 'some url'

response = requests.get(
    'the api url',
    auth=(api_key, api_secret))

data = response.json()

for tags in data['result']['tags']:
    tags = tags['tag']['en']
    img_list = tags.split(",") #convert values to a list
    list_str = ','.join([str(elem) for elem in img_list]) #converts list to a string
    print(list_str)

The data I'm getting back is JSON then, I put it through a loop to get our just the tags from the rest of the JSON. I convert it to a list, then to a string, but it's not a single string.

Sample of JSON:

{'result': {'tags': [{'confidence': 35.0027923583984, 'tag': {'en': 'machinist'}}, {'confidence': 30.3697471618652, 'tag': {'en': 'seller'}}, {'confidence': 28.2139053344727, 'tag': {'en': 'man'}}, {'confidence': 27.542501449585, 'tag': {'en': 'work'}}, {'confidence': 23.9936943054199, 'tag': {'en': 'worker'}}, {'confidence': 23.8494567871094, 'tag': {'en': 'working'}}, {'confidence': 23.012264251709, 'tag': {'en': 'person'}}, {'confidence': 21.2697811126709, 'tag': {'en': 'male'}}, {'confidence': 21.2244606018066, 'tag': {'en': 'job'}}, {'confidence': 18.9516372680664, 'tag': {'en': 'people'}}, {'confidence': 18.8158016204834, 'tag': {'en': 'construction'}}, {'confidence': 17.44016456604, 'tag': {'en': 'equipment'}}, {'confidence': 17.0697708129883, 'tag': {'en': 'industry'}}, {'confidence': 16.7942485809326, 'tag': {'en': 'stall'}}, {'confidence': 16.7873115539551, 'tag': {'en': 'steel'}}, {'confidence': 14.6504859924316, 'tag': {'en': 'tool'}}, {'confidence': 13.7434034347534, 'tag': {'en': 'occupation'}}, {'confidence': 13.6098012924194, 'tag': {'en': 'industrial'}}, {'confidence': 12.9942970275879, 'tag': {'en': 'machine'}}, {'confidence': 12.951189994812, 'tag': {'en': 'barbecue'}}, {'confidence': 12.873197555542, 'tag': {'en': 'men'}}, {'confidence': 12.8699989318848, 'tag': {'en': 'iron'}}, {'confidence': 12.6433362960815, 'tag': {'en': 'labor'}}, {'confidence': 12.5361061096191, 'tag': {'en': 'old'}}, {'confidence': 12.5158472061157, 'tag': {'en': 'skill'}}, {'confidence': 12.329460144043, 'tag': {'en': 'carpenter'}}, {'confidence': 11.9580173492432, 'tag': {'en': 'home'}}, {'confidence': 11.7145328521729, 'tag': {'en': 'manual'}}, {'confidence': 11.4941291809082, 'tag': {'en': 'repair'}}, {'confidence': 10.9860734939575, 'tag': {'en': 'adult'}}, {'confidence': 10.698281288147, 'tag': {'en': 'factory'}}, {'confidence': 10.5328407287598, 'tag': {'en': 'building'}}, {'confidence': 10.4540967941284, 'tag': {'en': 'metal'}}, {'confidence': 10.4486179351807, 'tag': {'en': 'tools'}}.........

print(img_list) gives me:

['machinist']
['seller']
['man']
['work']
['worker']
['working']
['person']
etc... 

print(list_str) gives me the closest result, but they're on different lines and isn't one string:

machinist
seller
man
work
worker
working
person
etc....

I've also tried csv = ",".join(tags) but it comma separates the values themselves like below

m,a,c,h,i,n,i,s,t
s,e,l,l,e,r
m,a,n
w,o,r,k
w,o,r,k,e,r
w,o,r,k,i,n,g
p,e,r,s,o,n

The question: How can I get the data back as a comma delimited string like: machinist,seller,man,work,worker,working,person ?

There is a problem with getting items from json. Here is the way to get all items in image_list correctly:

data = {'result':
 {'tags': [
     {'confidence': 35.0027923583984,
      'tag': {'en': 'machinist'}},
     {'confidence': 30.3697471618652,
      'tag': {'en': 'seller'}},
     {'confidence': 28.2139053344727,
      'tag': {'en': 'man'}},
     {'confidence': 27.542501449585,
      'tag': {'en': 'work'}},
     {'confidence': 23.9936943054199,
      'tag': {'en': 'worker'}},
     {'confidence': 23.8494567871094,
      'tag': {'en': 'working'}},
     {'confidence': 23.012264251709,
      'tag': {'en': 'person'}}
     ]
  }
}


image_list = []
for tags in data['result']['tags']:
    # Check whether confidence is > 20 or not
    # if so add it to list, else do nothing
    if tags['confidence'] > 20:
        image_list.append(tags['tag']['en']) 

# image_list -> ['machinist', 'seller', 'man', ...]

result = ",".join(image_list)
# -> 'machinist,seller,man,.."

I wrote this before I saw the json response. Hope still helps!

Otherwise, just going of what you have here:

# to print as list

# take your list of lists 

results = [
    ['machinist'],
    ['seller'],
    ['man'],
    ['work'],
    ['worker'],
    ['working'],
    ['person']
    ]
# create a list to store your string results

results_string = []

# loop through your results
# r is a list, step in to extract value
# append value to results_string list 

for r in results: 
    results_string.append(r[0])

# print results_string 
  print(results_string)

['machinist', 'seller', 'man', 'work', 'worker', 'working', 'person']

# To print as string:
# use enumerate to grab an index and value 
# if i is less than length results - 1
# print with a comma, else print no comma   

for i, r in enumerate(results_string):
    if i < (len(results_string) - 1):
        print(r, end=', ')
else:
    print(r)

machinist, seller, man, work, worker, working, person

You could create an empty list outside of the loop, add items to it, and then convert that list to a comma separated string once the loop has finished.

Assuming tags['tag']['en'] only ever returns a single value (it looks like it does), you could do:

tags_list = []  # Create an empty list

for tags in data['result']['tags']:

    tags_list.append(tags['tag']['en'])  # Add a tag to the list

comma_separated_tags = ','.join(tags_list)  # Convert list of tags to comma separated string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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