简体   繁体   English

从python列表中的字符串替换字符

[英]Replacing characters from string in python list

I have a list of names of apple products in random format.我有一个随机格式的苹果产品名称列表。 like take a single product name iphone 11 pro which can be found比如取一个单品名称iphone 11 pro可以查到

Iphone 11 Pro or iphone 11 Pro , or anything that can be. Iphone 11 Proiphone 11 Pro或任何可能的东西。 But i want to change this to the naming pattern how the apple gives them, eg : iPhone 11 Pro但我想将其更改为苹果给它们的命名模式,例如: iPhone 11 Pro

So, I'm trying to change all of then first to title and then replacing first two characters of the string.所以,我试图先将所有内容更改为标题,然后替换字符串的前两个字符。 but problem is second part is not working.但问题是第二部分不起作用。 Being a beginner im not able to reproduce the solution.作为初学者,我无法重现该解决方案。 I have read the article about regex in python.我已阅读有关 python 中的正则表达式的文章。 but unable to find better way to do it.但无法找到更好的方法来做到这一点。

Thats how im trying..我就是这样努力的。。

names = ['Iphone 12', 'iphone 11 pro', 'IPad pro', 'Imac pro']
titled_names = []
updated_names = []

# first change all to title
for i in names:
    i.title()
    titled_names.append(i)

# replace the first two char
for i in titled_names:
    i.replace('Ip', 'iP', 1)
    updated_names.append(i)

print(updated_names)

But this should not supposed to work in anyway as there can some products where first char wont be Ip, like in the Imac.但这不应该无论如何都可以工作,因为有些产品的第一个字符不会是 Ip,比如在 Imac 中。 the end result of the names list should be like this.名称列表的最终结果应该是这样的。

names = ['iPhone 12', 'iPhone 11 Pro', 'iPad Pro', 'iMac Pro']

so how can I achieve this.那么我怎样才能做到这一点。 first char small second capital in first letter, and rest in Title Case第一个字符在第一个字母中小写第二个大写字母,其余在标题大小写中

You can specify the list of desired namings.您可以指定所需命名的列表。

# update to your needs
CORRECT_STRINGS = ["Apple", "iPhone", "iPad", "iMac", "MacBook", "Pro", "SE", "Max"]

names = ['Iphone 12', 'iphone 11 pro', 'IPad pro', 'Imac pro']

new_names = []

for name in names:
    # convert to lower-case
    correct_name = name.lower()

    # replace all matching string to correct one
    for correct_string in CORRECT_STRINGS:
        # we want to find a lower-case string and replace it
        match_string = correct_string.lower()
        correct_name = correct_name.replace(match_string, correct_string)

    # add correct device name to the result list   
    new_names.append(correct_name)

print(new_names)
>>> ['iPhone 12', 'iPhone 11 Pro', 'iPad Pro', 'iMac Pro']

Although, this approach might not always work properly if some name is a substring of another name.虽然,如果某个名称是另一个名称的子字符串,这种方法可能并不总是正常工作。 With Apple product this might not be the case.对于 Apple 产品,情况可能并非如此。

UPDATE: a more elegant solution (replaces only fully matched strings)更新:更优雅的解决方案(仅替换完全匹配的字符串)

# update to your needs
DEVICE_NAME_STRINGS = [
    "Apple",
    "iPhone",
    "iPad",
    "iMac",
    "MacBook",
    "Pro",
    "SE",
    "Max",
]
DEVICE_NAME_STRINGS_MAP = {s.lower(): s for s in DEVICE_NAME_STRINGS}

names = ['Iphone 12', 'iphone 11 pro', 'IPad pro', 'Imac pro']


def standardize_device_name(device_name: str):
    """
    Example: iPhOnE 13 PrO mAx -> iPhone 13 Pro Max
    """
    return " ".join(
        [
            DEVICE_NAME_STRINGS_MAP.get(word.lower(), word)
            for word in device_name.split()
        ]
    )


new_names = [standardize_device_name(name) for name in names]

print(new_names)

I've done some changes and use another approach.我做了一些改变并使用了另一种方法。 Here I wrote function to take and return all list members with first letter in lower case.在这里,我编写了函数来获取并返回所有首字母小写的列表成员。 If you need second letter as well, you can add second letters index as lower as well(added in comment).如果您还需要第二个字母,您也可以将第二个字母索引添加得更低(在评论中添加)。 This is simplest way for beginner I guess.我猜这是初学者最简单的方法。

def first_letter_to_lower(givenList):
  for i in givenList:
      i = i[0].lower() + i[1::]
      print(i)


first_letter_to_lower(names)

OUTPUT

iphone 12
iphone 11 pro
ipad pro
imac pro

If you like to have your list back, you can add an append method in the function to return i.lowwered in "givenList"如果你想恢复你的列表,你可以在函数中添加一个 append 方法以在“givenList”中返回 i.lowwered

Works like a charm!奇迹般有效!

def capitalize_nth(s, n):
    """This function will capitalize nth charcater in string"""
    return s[:n].lower() + s[n:].capitalize()

def edit_strings(name):
    # convert given string to lowercase and strip any whitespace infront & back
    name = name.lower().strip()
    
    # split string based on first space, since we need to capitalize second character only for the first substring(product name)
    # Eg: ['iphone', '12']
    sub_strs = name.split(" ", 1)
    
    return " ".join([
            capitalize_nth(sub_strs[0], 1), # capitalize second character of product name
            sub_strs[1].title() # capitalize first character of each word in string
        ])
    
    
        
    
names = ['Iphone 12', 'iphone 11 pro', 'IPad pro', 'Imac pro', 'iphone 12 pro max']
edited_names = [edit_strings(name) for name in names]
print(edited_names)

Output:输出:

['iPhone 12', 'iPhone 11 Pro', 'iPad Pro', 'iMac Pro', 'iPhone 12 Pro Max']

You'll need to append the values returned by the string methods into your lists:您需要将字符串方法返回的值附加到您的列表中:

names = ['Iphone 12', 'iphone 11 pro', 'IPad pro', 'Imac pro']
titled_names = []
updated_names = []

# first change all to title
for i in names:
    titled_names.append(i.title())

# replace the first two char
for i in titled_names:
    updated_names.append(i.replace('Ip', 'iP', 1))

print(titled_names)
print(updated_names)

Output:输出:

['Iphone 12', 'Iphone 11 Pro', 'Ipad Pro', 'Imac Pro']
['iPhone 12', 'iPhone 11 Pro', 'iPad Pro', 'Imac Pro']

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

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