【问题标题】:How to change the lower case to upper case with conditional specific string in python如何在python中使用条件特定字符串将小写更改为大写
【发布时间】:2020-07-08 06:18:33
【问题描述】:

我在数据框中有一些文本,其中我想要一些大写的特定水果。文字如下 输入是

one apple
two oranges
three bananas
an apple

和 所需的输出是

one Apple
two Oranges
three Bananas
an Apple

如果数组/字符串/列表有任何单词“one”、“two”、“three”和“an”,我可以给出条件的循环(条件当这些......任何单词在字符串中时) ,在这个词之后,将下一个词的首字母小写改为大写。

如果有任何提示或帮助。

5 行数据 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ +

ID Reference_time Comment
0 0059 one apple box
1 0156 five oranges left
2 1859 an engineer handling issue
3 1555 two persons have eaten, three still hungry
4 2109 an apple carton is still in stock

++++++++++++++++++++++++++++++++++++++++++++++++++ ++++

【问题讨论】:

  • 您甚至没有阅读文本文件并创建数据框吗?
  • 我已经导入了。它已经在数据框中。但它是如此之大。我不能放置整个。我只能给出像上面这样的小 3/4 行
  • 那么分享一个样本,比如前 5 行,列名
  • 您介意分享您的尝试吗?
  • 这个用于大小写更改的条件循环,我什至无法构建,所以寻求帮助

标签: python regex pandas


【解决方案1】:

使用正则表达式可能是更好的方法,但这应该使用.str.extract

唯一的缺点是,如果您在单个字符串中有多个匹配项,则需要处理/编辑正则表达式。

repl = ['one','two','three','five','an']
pat = '|'.join(repl)


s = df["comment"].str.extract(rf"({pat})(.*\w.*$)")

s[1] = s[1].str.strip().str.capitalize()
df['comment_new'] = s.stack().groupby(level=0).agg(' '.join)

print(df[['comment_new','comment']])

                                  comment_new  \
0                               one Apple box   
1                           five Oranges left   
2                  an Engineer handling issue   
3  two Persons have eaten, three still hungry   
4           an Apple carton is still in stock   

                                      comment  
0                               one apple box  
1                           five oranges left  
2                  an engineer handling issue  
3  two persons have eaten, three still hungry  
4           an apple carton is still in stock 

【讨论】:

    【解决方案2】:
    keywords = ['one', 'two', 'three', 'an']
    
    df['Comment'] = df['Comment'].apply(lambda x: toUpper(keywords, x))
    
    def toUpper(keywords, sentence):
      word_list = sentence.split()
      for i in range(len(word_list)-1):
        if word_list[i] in keywords:
            word_list[i+1] = word_list[i+1].capitalize()
    
      return ' '.join(word_list)
    

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 2019-07-20
      • 2011-12-04
      • 2011-10-06
      • 1970-01-01
      • 2021-03-30
      • 2014-02-04
      • 2014-04-20
      • 1970-01-01
      相关资源
      最近更新 更多