删除csv文件中不需要的引号和逗号

时间:2019-05-02 15:06:08

标签: python

我需要从csv文件中删除不需要的引号和逗号。样本数据如下

public class AccountSettings extends AppCompatActivity {

    private CircleImageView setupImage;
    private Uri mainImageUri = null;
    private EditText setupName;
    private Button setupBtn;
    private StorageReference storageReference;
    private FirebaseAuth firebaseAuth;
    private ProgressDialog progressDialog;
    private FirebaseFirestore firebaseFirestore;
    private String user_id;
    StorageReference image_path;
    private boolean isChanged = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_settings);

        Toolbar setupToolbar = findViewById(R.id.setupToolbar);
        setSupportActionBar(setupToolbar);
        getSupportActionBar().setTitle("Account Settings");

        firebaseAuth = FirebaseAuth.getInstance();
        storageReference = FirebaseStorage.getInstance().getReference();
        user_id = firebaseAuth.getCurrentUser().getUid();
        setupName = findViewById(R.id.setup_name);
        setupBtn = findViewById(R.id.setup_btn);
        setupImage = findViewById(R.id.setupImage);
        progressDialog = new ProgressDialog(this);
        firebaseFirestore = FirebaseFirestore.getInstance();
        image_path = storageReference.child("Profile_Images").child(user_id + ".jpg");

        firebaseFirestore.collection("Users").document("user_id").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if(task.isSuccessful()){

                    if(task.getResult().exists()){

                        String name = task.getResult().getString("name");
                        String image = task.getResult().getString("image");

                        setupName.setText(name);

                        RequestOptions placeholderRequest = new RequestOptions();
                        placeholderRequest.placeholder(R.drawable.accountprofile);

                        Glide.with(AccountSettings.this).setDefaultRequestOptions(placeholderRequest).load(image).into(setupImage);

                    }
                }
                else{
                    String error = task.getException().getMessage();
                    Toast.makeText(AccountSettings.this,"Firestore Retrieval Error!"+error,Toast.LENGTH_LONG).show();
                }
            }
        });

        setupBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.setMessage("Loading please wait...");
                progressDialog.show();
                final String user_name = setupName.getText().toString();
                if(isChanged) {

                    if (!TextUtils.isEmpty(user_name) && mainImageUri != null) {
                        final String user_id = firebaseAuth.getCurrentUser().getUid();

                        final StorageReference image_path = storageReference.child("profile_images").child(user_id + ".jpg");
                        image_path.putFile(mainImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                                if (task.isSuccessful()) {

                                    storeFirestore(task, user_name);

                                } else {
                                    String error = task.getException().getMessage();
                                    Toast.makeText(AccountSettings.this, "Image Error: " + error, Toast.LENGTH_SHORT).show();

                                }
                                progressDialog.dismiss();
                            }
                        });

                    }
                }
                else{
                    storeFirestore(null,user_name);
                }
            }
        });

      setupImage.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {

              if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

                  if(ContextCompat.checkSelfPermission(AccountSettings.this, Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){

                      Toast.makeText(AccountSettings.this, "Permission Denied!",Toast.LENGTH_LONG).show();
                      ActivityCompat.requestPermissions(AccountSettings.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);

                  } else {
                      BringImagePicker();
                  }

              }
              else{
                  BringImagePicker();
              }
          }
      });
    }

    private void storeFirestore( Task<UploadTask.TaskSnapshot> task,String user_name) {
            Uri download_uri;
        if(task != null){
          download_uri = Uri.parse(task.getResult().getMetadata().getReference().getDownloadUrl().toString());
        }
        else {
            download_uri = mainImageUri;
        }
        Map<String, Object> user_map = new HashMap<>();
        user_map.put("name", user_name);
        user_map.put("image", download_uri);
        firebaseFirestore.collection("Users").document(user_id).set(user_map).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if(task.isSuccessful()){

                    startActivity(new Intent(AccountSettings.this, MainActivity.class));
                    finish();
                }
                else{
                    String error = task.getException().getMessage();
                    Toast.makeText(AccountSettings.this,"Firestore Error: " +error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void BringImagePicker(){
        CropImage.activity()
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(1,1)
                .start(AccountSettings.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode,resultCode,data);
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                mainImageUri = result.getUri();
                setupImage.setImageURI(mainImageUri);
                isChanged = true;
            } else if(resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE){
                Exception error = result.getError();
            }
        }
    }
}

最后一列具有一些自由文本值,这些值看起来像一个新列,但是它在excel中打开,然后看起来像这样

header1, header2, header3, header4
1,       "ABC",   BCD,     "EDG",GHT\2\TST"

请指导我修复最后一列。

尝试过-

EDG",GHT\2\TST

2 个答案:

答案 0 :(得分:0)

这应该从列中找到",,然后将其替换为空

df = df.str.replace('[",]','',regex=True)

答案 1 :(得分:0)

您可以这样:

with open("data.txt", "r") as f:
        for line in f.readlines():
                columns = line.split(", ") # Split by ", "
                columns[3] = "".join(columns[3:]) # Merge columns 4 to ... last
                columns[3] = columns[3].replace("\"", "").replace(",", "")` # Removing unwanted characters
                del columns[4:] # Remove all unnecessary columns

                print("%s | %s | %s | %s" % (columns[0], columns[1], columns[2], columns[3]))

我的data.txt文件:

1, "ABC", BCD, "EDG",GHT\2\TST"
2, "CBA", DCB, "GDV",DHZ,\2RS"

输出:

1 | "ABC" | BCD | EDGGHT\2\TST

2 | "CBA" | DCB | GDVDHZ\2RS

如果仅最后一列包含逗号,则此解决方案将起作用。